Reputation:
I have a values
state. It's an empty array.
On componentDidMount I take values from API, this action set new state with an array like this:
[
435235324: { data: ... },
456565767: { data: ... }
]
Each number is an id.
I have websocket for new data in each id, So I need update data value of array item.
My search function is:
const setNewValueToState = (id, data) => {
const exist = widgetValues[id];
console.log(exist)
if(!exist){
setWidgetValues(oldValues => [...oldValues, oldValues.id = data ])
}
}
I need to check if id exist on array, if not, "push it" on.
But it doesn't work. It return an infinite array like this:
[
{ data: ... },
{ data: ... }
]
An array without key :/
Upvotes: 0
Views: 71
Reputation: 356
Agreed with @Drusto 's answer. The array structure is not correct. it should be
var oldObj = {
435235324: {},
456565767: {}
};
And finally you can do
var newObj = {...oldObj, 435235324:{yourKey: "yourVal"}}
Also your setWidgetValues I need to see.
Upvotes: 0
Reputation: 6957
Assuming your state looks like this:
[{id: '123', data: ...}]
This is not a valid data structure:
[123: {data ...}]
let data = [{
id: 993,
data: 'foo'
}, {
id: 123,
data: 'bar'
}];
let idToSearch = 123;
for (let i = 0; i < data.length; i++) {
if (data[i].id = idToSearch) {
// found it, it's data[i]
console.log('Found:', data[i]);
break; // exit the loop!
}
}
Or new hot stuff which I tend to avoid because I usually work with very big datasets and every ms
counts (invokes a callback for each index). But it's totally fine with small or medium arrays in most environments:
const found = data.find(item => item.id === idToSearch);
Upvotes: 0
Reputation: 547
[
435235324: { data: ... },
456565767: { data: ... }
]
Is not a valid array structure, as the others comments say, you should use an array of objects
[
{
"id":123456,
"data":{
....
}
},
{
"id":1234567,
"data":{
....
}
},
]
Or use an object
{
123:{
data:{}
},
1234:{
data:{}
},
}
Upvotes: 1