Reputation: 792
I am trying to add data to nested array and already tried out many stackoverflow links to solve out this problem but failed to do so.
Original Data:
cuisine: [
[
"Middle Eastern",
4
],
[
"Western",
4
],
[
"Pasta Dishes",
2
],
[
"Salad",
2
],
[
"Mexican",
1
],
[
"Soup",
1
],
[
"snacks",
1
]
],
Desired Data:
cuisine: [
[
1
false
"Middle Eastern",
4
],
[
2
false
"Western",
4
],
[
3
false
"Pasta Dishes",
2
],
[
"Salad",
2
],
[
4
false
"Mexican",
1
],
[
5
false
"Soup",
1
],
[
6
false
"snacks",
1
]
],
My code
this.setState({ cousineArray: cuisine }, () => {
this.addValuesToArray(this.state.cousineArray);
});
addValuesToArray = commingArray => {
console.warn(commingArray);
if (commingArray !== null && commingArray !== undefined) {
for (i = 0; i < commingArray.length; i++) {
this.setState(
{
commingArray: this.state.commingArray.push(i, false)
},
() => {
console.log("Coming Array ==> ", commingArray[1]);
}
);
}
}
};
but its not working and throwing following error
Cannot read property 'push' of undefined
What thing I am doing wrong. please tell me the better way if this is not well way to do this. Thanks
Upvotes: 2
Views: 234
Reputation: 12152
Use forEach
loop to push values in the array using your own logic
var cuisine= [
[
"Middle Eastern",
4
],
[
"Western",
4
],
[
"Pasta Dishes",
2
],
[
"Salad",
2
],
[
"Mexican",
1
],
[
"Soup",
1
],
[
"snacks",
1
]
]
cuisine.forEach(function(e,j){
e.unshift(false)
e.unshift(j)
e.unshift({key:'value'})
})
console.log(cuisine)
Upvotes: 1
Reputation: 10873
Do not set state in a loop, also use map
to properly set values to your nested array:
addValuesToArray = commingArray => {
console.warn(commingArray);
if (commingArray !== null && commingArray !== undefined) {
const res = commingArray.map(arr => {
return arr.map((innerArr, i) => {
return [...innerArr, i, false]
})
})
this.setState({
commingArray: res
},
() => {
console.log("Coming Array ==> ", commingArray);
}
);
}
}
Upvotes: 2