Push adds array to array instead of elements [duplicate] - javascript

This question already has answers here:
Merge 2 arrays of objects
(46 answers)
Closed 1 year ago.
I need to get some data from API and store it in array. If I set value to it as assigning through = the returned data is displayed as I need. But if I use push to add elements they are added as another array.
It is console log of array after first assigning this.elements = response.data
Proxy {0: {…}, 1: {…}, 2: {…}}
[[Handler]]: Object
[[Target]]: Array(3)
0: {ID: 40, created_at: "2021-03-13T22:15:09.769066+03:00", updated_at: "2021-03-13T22:15:09.769066+03:00", DeletedAt: null, user_id: 19, …}
1: {ID: 39, created_at: "2021-03-13T22:15:06.779473+03:00", updated_at: "2021-03-13T22:15:06.779473+03:00", DeletedAt: null, user_id: 19, …}
2: {ID: 38, created_at: "2021-03-13T22:15:01.738319+03:00", updated_at: "2021-03-13T22:15:01.738319+03:00", DeletedAt: null, user_id: 19, …}
length: 3
__proto__: Array(0)
[[IsRevoked]]: false
And it is through push method this.elements .push(response.data)
Proxy {0: {…}, 1: {…}, 2: {…}, 3: Array(3)}
[[Handler]]: Object
[[Target]]: Array(4)
0: {ID: 40, created_at: "2021-03-13T22:15:09.769066+03:00", updated_at: "2021-03-13T22:15:09.769066+03:00", DeletedAt: null, user_id: 19, …}
1: {ID: 39, created_at: "2021-03-13T22:15:06.779473+03:00", updated_at: "2021-03-13T22:15:06.779473+03:00", DeletedAt: null, user_id: 19, …}
2: {ID: 38, created_at: "2021-03-13T22:15:01.738319+03:00", updated_at: "2021-03-13T22:15:01.738319+03:00", DeletedAt: null, user_id: 19, …}
3: Array(3)
0: {ID: 38, created_at: "2021-03-13T22:15:01.738319+03:00", updated_at: "2021-03-13T22:15:01.738319+03:00", DeletedAt: null, user_id: 19, …}
1: {ID: 33, created_at: "2021-03-13T10:59:06.521453+03:00", updated_at: "2021-03-13T10:59:06.521453+03:00", DeletedAt: null, user_id: 19, …}
2: {ID: 32, created_at: "2021-03-13T10:58:59.111903+03:00", updated_at: "2021-03-13T10:58:59.111903+03:00", DeletedAt: null, user_id: 19, …}
length: 3
__proto__: Array(0)
length: 4
__proto__: Array(0)
[[IsRevoked]]: false
How can I add elements of the array instead of the array itself?

You can use push with spread operator:
this.elements.push(...response.data)
E.g.
const arr1 = [1, 2, 3];
const arr2 = [12, 13, 14];
arr1.push(...arr2);
console.log(arr1);

You could use spread operator to concatenate the original array with the new one :
this.elements =[...this.elements, ...response.data]

Related

Accessing objects inside arrays

My API is returning the below response. I am trying to filter through the links to check if the source and target name properties in each object match a specific string. Any idea how I can do this, I am have troubling getting to the name property.
Currently this.chart.links.target.name and this.chart.links.source.name are returning undefined. I cannot seem to access the name properties.
Proxy {nodes: Array(69), links: Array(68)}
[[Handler]]: Object
[[Target]]: Object
links: Array(68)
0:
circular: false
index: 0
real_value: 10
source: {name: 'String1', color: 'yellow', index: 30, sourceLinks: Array(30), targetLinks: Array(24), …}
target: {name: 'String2', color: 'red', index: 0, sourceLinks: Array(0), targetLinks: Array(1), …}
value: 10
width: 2.152297042164877
y0: 111.36731918963686
y1: 193.80113278791737
[[Prototype]]: Object
1: {source: {…}, target: {…}, value: 10, real_value: 10, index: 1, …}
2: {source: {…}, target: {…}, value: 10, real_value: 10, index: 2, …}
3: {source: {…}, target: {…}, value: 10, real_value: 10, index: 3, …}
4: {source: {…}, target: {…}, value: 10, real_value: 10, index: 4, …}
5: {source: {…}, target: {…}, value: 10, real_value: 10, index: 5, …}
6: {source: {…}, target: {…}, value: 10, real_value: 10, index: 6, …}
7: {source: {…}, target: {…}, value: 10, real_value: 10, index: 7, …}
this is how my filter is looking:
const dataToFilter = ['String1', 'String2']
const links = this.chart.links.filter(io =>
!dataToFilter.includes(io.source.name || io.target.name)
)
Instead of !dataToFilter.includes(io.source.name || io.target.name) you want to have !(dataToFilter.includes(io.source.name) || dataToFilter.includes(io.target.name)) to check against the names separately.

Unexpected effect: Making a copy of an object modifies it

Context:
I have a component whichj emits data to the parent. Parent has two default objects-An empty array, and another object which contains default values, which are used to add a new element to the array using the data passed.
Template:
<billing-search
:search-term="searchText"
:show-modal="showBillingModal"
#closeModal="CloseBillingModal"
#selectedAnItem="AddSelectedItem"
/>
Initial data:
data() {
return {
billitems: [],
billitem_def: {
invitem: null,
procitem: null,
stockid: null,
qty: 0,
unitprice: 0,
discpercent: 0,
disc: 0,
}
}
},
My method in the parent triggered on emiting from the component, is this:
AddSelectedItem(data) {
console.log(`In AddSelectedItem`);
console.log(`this.billitems was `, this.billitems);
console.log(`Got data passed by component:`, data);
let newitem = this.billitem_def
console.log(`this.billitems was `, this.billitems);
newitem.invitem = data.item
newitem.stockid = data.storeitem
newitem.unitprice = newitem.stockid.mrp
console.log(`Added new item to billing list:`);
console.log(newitem);
this.billitems.push(newitem)
console.log(`this.billitems is now `, this.billitems);
console.log(`this.billitem_def is `, this.billitem_def);
},
See an example of console log:
In AddSelectedItem
BillingBlock.vue?670b:173 this.billitems was
0:
disc: 0
discpercent: 0
invitem: {id: 50, name: 'Waxonil Activ Ear Drops', description: 'Adult ear drops', itemtype: 4, clinic: 10, …}
procitem: null
qty: 0
stockid: {id: 432, entry: {…}, item: {…}, quantity: 30, stock: 21, …}
unitprice: "119.30"
BillingBlock.vue?670b:174 Got data passed by component:
{
item: {
clinic: 10
description: "Adult ear drops"
drugid: null
id: 50
isOpen: true
itemtype: 4
name: "Waxonil Activ Ear Drops"
storeitem: (13) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
},
storeitem: {
batchnum: "SW135"
entry: {id: 275, entry_number: 'WjazQPLxb', reference_number: '', invoice_number: 'A-50864', entry_date: '2021-12-20', …}
expirydate: "2024-08-21"
id: 432
item: {id: 50, name: 'Waxonil Activ Ear Drops', description: 'Adult ear drops', itemtype: 4, clinic: 10, …}
manufacturedate: null
}
}
BillingBlock.vue?670b:177 this.billitems was
Proxy {
0:
disc: 0
discpercent: 0
invitem: {id: 50, name: 'Waxonil Activ Ear Drops', description: 'Adult ear drops', itemtype: 4, clinic: 10, …}
procitem: null
qty: 0
stockid: {id: 432, entry: {…}, item: {…}, quantity: 30, stock: 21, …}
unitprice: "119.30"
}
BillingBlock.vue?670b:181 Added new item to billing list:
BillingBlock.vue?670b:182
Proxy {invitem: {…}, procitem: null, stockid: {…}, qty: 0, unitprice: '119.30', …}
BillingBlock.vue?670b:185 this.billitems is now
Proxy {0: {…}}
BillingBlock.vue?670b:186 this.billitem_def is
Proxy { invitem: {… }, procitem: null, stockid: {… }, qty: 0, unitprice: '119.30', … }
Problems with this:
The this.billitems was shows data even before it is being assigned, instead of an empty array
this.billitem_def was set to some null values initially in the data part. It was not meant to get values, but to serve as a template of default data. Though I had let newitem = this.billitem_def, how is this.billitem_def's data getting modified? I dont have code anywhere in the project assigning this.billitem_def to anything else.

Not displaying data from console.log

I'm working on a project in react, which I console.log a data and it shows, but when i try to display, its not working. I think im missing something. Its not displaying the length, id or body of the content
<Badge count={`${notify !== null ? notify.length : 0}`} overflowCount={10}>
<Dropdown
overlay={<Menu>
{notify && notify.map(notify => {
return (
<Menu.Item key={notify.id}>
{notify.body}
</Menu.Item>
);
})}
{notify && notify.length < 1 ? (
<Menu.Item>No notifications yet</Menu.Item>
) : null }
<Menu.Divider />
<Menu.Item onClick={() =>
this.props.history.push("/notifications")
}>
VIEW ALL <ArrowRightOutlined /></Menu.Item>
</Menu>
}
trigger={['click']}>
<a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
<BellOutlined style={{ fontSize: '25px', color: '#2aa515' }}/>
</a>
</Dropdown>
</Badge>
This is the data from the console.log
(21) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
assigned_to: 4
body: "tayodami followed you! ID: 12"
creation_date: "2020-10-10T19:41:23.428773Z"
group: "NF"
id: 21
is_read: true
pk_relation: 12
__proto__: Object
1: {id: 22, group: "NF", creation_date: "2020-10-10T19:43:27.537867Z", is_read: true, body: "que followed you! ID: 13", …}
2: {id: 23, group: "NF", creation_date: "2020-10-10T20:05:06.098263Z", is_read: true, body: "oladeji followed you! ID: 14", …}
3: {id: 24, group: "NF", creation_date: "2020-10-11T05:41:46.792794Z", is_read: true, body: "oladeji followed you!", …}
4: {id: 25, group: "NC", creation_date: "2020-10-11T10:39:02.069264Z", is_read: true, body: "que commented: asfasf.", …}
5: {id: 26, group: "NC", creation_date: "2020-10-11T10:40:26.915029Z", is_read: true, body: "que commented: asfasf.", …}
6: {id: 28, group: "NC", creation_date: "2020-10-11T11:36:50.180718Z", is_read: true, body: "que commented: hi.", …}
7: {id: 29, group: "NC", creation_date: "2020-10-11T11:45:38.079017Z", is_read: true, body: "que commented: gg on your post.", …}
8: {id: 31, group: "NC", creation_date: "2020-10-12T11:46:50.121499Z", is_read: true, body: "que commented: hi on your post.", …}
9: {id: 32, group: "NC", creation_date: "2020-10-12T11:50:42.081770Z", is_read: true, body: "que commented: "TODAY" on your pop.", …}
...
length: 21
__proto__: Array(0)
Use console.dir() instead of .log() to get all fields.
https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

cannot change scope property

im trying to change an property value into the $scope variable of angular js, but the applied changes has not been setted.
my code is this:
in my code i have an costBudget with many childs into an array, and i need to reeplace these child for the costWorkPackages array.
let costBudget = $scope.list[0];
costBudget.subCostsWorkPackages = costsWorkPackages;
console.log(costBudget);
the costBudget variable is the same before and after to assign the new array, and its wrong. I expect the costBudget has the new childs, but does not happens.
UPDATED:
added console objects:
before the change:
{code: 1, internalId: 0, notRealWorkPackage: true, name: "shrh",
count: 1, …}
$$hashKey: "object:190"
code: 1
subCostsWorkPackages: Array(3)
0: Resource {id: 6491, name: "ascasca", count: 1,
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
1: Resource {id: 6492, name: "ascasca", count: 1,
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
2: Resource {id: 6493, name: "ascasca", count: 1,
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
$promise: Promise {$$state: {…}}
$resolved: true
length: 3
__proto__: Array(0)
subNodeClass: ""
title: "shrh"
toggleButtonClass: "fa-minus-square-o"
__proto__: Object
after:
{code: 1, internalId: 0, notRealWorkPackage: true, name: "shrh",
count: 1, …}
$$hashKey: "object:190"
code: 1
subCostsWorkPackages: Array(3)
0: Resource {id: 6491, name: "ascasca", count: 1, subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
1: Resource {id: 6492, name: "ascasca", count: 1, subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
2: Resource {id: 6493, name: "ascasca", count: 1, subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
$promise: Promise {$$state: {…}}
$resolved: true
length: 3
__proto__: Array(0)
subNodeClass: ""
title: "shrh"
toggleButtonClass: "fa-minus-square-o"
__proto__: Object
UPDATE 2:
costsWorkPackage variable in console:
[Resource, Resource, Resource, Resource, $promise: Promise, $resolved:
true]
0: Resource {id: 6430, name: "Nombre 2", count: "1.00000000",
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
1: Resource {id: 6437, name: "Nombre 9", count: "1.00000000",
subCostsWorkPackages: Array(0), resourceInstances: Array(0), …}
2: Resource {id: 6438, name: "Nombre 3", count: "1.00000000",
subCostsWorkPackages: Array(5), resourceInstances: Array(2), …}
3: Resource {id: 6431, name: "Nombre 3", count: "1.00000000",
subCostsWorkPackages: Array(5), resourceInstances: Array(2), …}
$promise: Promise {$$state: {…}}
$resolved: true
length: 4
__proto__: Array(0)

React mapping objects, targeting errors

I have some troubles mapping fetched objects, i know it's a known problem but it's been two days i'm stuck so i come asking for some help.
I'm trying to output data on an ul from an api but i either have errors or nothing gets output, i know that i am targeting my data inside my object the wrong way, it's the first time i'm trying to target an object with this kind of keys
I have an object 'names' looking like that:
[Array(20)]
0: Array(20)
0:
avatar: ""
country: "RU"
games: (3) [{…}, {…}, {…}]
nickname: "d2mash"
player_id: "07982364-a458-4a1f-b6d6-1be146db9126"
status: "AVAILABLE"
verified: true
__proto__: Object
1: {player_id: "cab2a609-de2f-4023-a9c7-af89d5292c96", nickname: "D0cC-", status: "BUSY", games: Array(1), country: "NL", …}
2: {player_id: "d67a944f-1c1d-4d75-a7bf-d52c4b30e7db", nickname: "r1d3Rz", status: "AVAILABLE", games: Array(1), country: "RO", …}
3: {player_id: "f40bef0d-d40a-48d0-8c53-5a513c35bd3a", nickname: "dotademon", status: "AVAILABLE", games: Array(1), country: "US", …}
4: {player_id: "dca784fa-546b-43b7-adf6-cf537d858d4f", nickname: "degeneral", status: "AVAILABLE", games: Array(2), country: "UA", …}
5: {player_id: "e72a43cd-d214-4d4c-989a-efb1d3e7df37", nickname: "daave-", status: "AVAILABLE", games: Array(1), country: "US", …}
6: {player_id: "4e093c2c-f277-4877-a200-029ae6d8602f", nickname: "ddk", status: "AVAILABLE", games: Array(5), country: "US", …}
7: {player_id: "ef629874-bf6e-4066-8612-09e0428e923c", nickname: "dieZzz", status: "AVAILABLE", games: Array(3), country: "RU", …}
8: {player_id: "77995857-d14d-47ed-a150-4f175f70654e", nickname: "durpdurp", status: "AVAILABLE", games: Array(1), country: "US", …}
9: {player_id: "e3ed56b6-138f-4141-b6c9-ba6eab7bfc24", nickname: "dengue", status: "AVAILABLE", games: Array(3), country: "PT", …}
10: {player_id: "d6bd0d6f-a068-4e10-b9a4-129297c8691f", nickname: "disco doplan", status: "BUSY", games: Array(2), country: "SE", …}
11: {player_id: "7e80ed2a-8e39-457e-95c2-1c9ba9449daf", nickname: "dupreeh", status: "BUSY", games: Array(1), country: "DK", …}
12: {player_id: "32772d2f-fb63-4a84-ac06-4c2e20f49082", nickname: "denis-", status: "AVAILABLE", games: Array(1), country: "DE", …}
13: {player_id: "089df523-86dd-4705-944f-f012adb5a0f8", nickname: "dream3r---", status: "AVAILABLE", games: Array(1), country: "BG", …}
14: {player_id: "b8b709e5-96f8-4cf5-8348-95b8b67e0b34", nickname: "DreadAV", status: "AVAILABLE", games: Array(1), country: "RU", …}
15: {player_id: "5fd703b0-6762-44c8-9284-b8f01ef70e71", nickname: "DendiGoD", status: "AVAILABLE", games: Array(1), country: "UA", …}
16: {player_id: "6c4f1a76-1341-4513-90ac-8d43dd1c86b6", nickname: "dipparn", status: "AVAILABLE", games: Array(1), country: "SE", …}
17: {player_id: "ae0bfe74-ec96-4499-910f-e02acd5be700", nickname: "DuBu-", status: "AVAILABLE", games: Array(1), country: "CA", …}
18: {player_id: "d6bc4849-5256-4463-a38e-bcd77fc31ff9", nickname: "device", status: "BUSY", games: Array(1), country: "DK", …}
19: {player_id: "4bb4503f-5272-40dc-8165-d050290db66a", nickname: "desi", status: "AVAILABLE", games: Array(1), country: "US", …}
length: 20
__proto__: Array(0)
length: 1
__proto__: Array(0)
Then i pass it to a component like that:
{
!isLoading &&
<PlayerSearchResult players={names} />
}
My component:
class PlayerSearchItem extends Component {
public render() {
return (
<li key={this.props.cle}>
<Link to={"#"}>nom - {this.props.pseudo}</Link>
</li>
);
}
}
class PlayerSearchResult extends Component {
public render() {
return (
<div>
<ul>
{Object.keys(this.props.players).map((player, i) => (
<PlayerSearchItem
cle={player[player].player_id}
pseudo={players[i]}
/>
))}
</ul>
</div>
);
}
}
don't mind the way I'm targeting my data, it's one of my many tries.
I think that your map looks wrong
This:
Object.keys(this.props.players).map((player, i) => ( <
PlayerSearchItem cle = {
player[player].player_id
}
pseudo = {
players[i]
}
/>
))
Should be:
Object.keys(this.props.players).map((player, i) => ( <
PlayerSearchItem cle = {
player.player_id
}
pseudo = {
player
}
key={player.player_id}
/>
))
Then from the screenshot of your data, it looks like you have as data an array of 20 items, which has as first element an array of 20 items, where the items from 1 to 20 are the real players.

Categories

Resources