here’s what I’m trying to do:
state={
show:true,
key:'',
sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}
I need to add elements to the data arrays and I need to add Objects to the sections array
here’s what I’m trying to do:
state={
show:true,
key:'',
sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}
I need to add elements to the data arrays and I need to add Objects to the sections array
Try the following:
var state={
show:true,
key:'',
sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}
state.sections.push({title:'new',data:['e','f']});
console.log(state.sections);
Pushing a new section is easy:
state.sections.push({title:'someTitle',data:[2, 3]});
To push new data, you need to specify which data you want to push to. For example to push into the test section, you must first get a reference to the test object, then push:
var state= {
show:true,
key:'',
sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}
let section = state.sections.find(item => item.title == 'test')
section.data.push(3)
console.log(state)
This assumes the titles are unique because find() only finds the first matching item. You might also want to test that find() actually found something if there's a chance you'll search for titles that don't exist.
Use the push() function to add item into an array:
let state={
show:true,
key:'',
sections: [{title:'primary',data:['a','b']},{title:'test',data:[1,2]}]
}
state.sections[0].data.push('c');
state.sections.push({title:'title',data:['2','5']});
console.log(state.sections);
//for react setState
this.setState({
state.sections: [...this.state.sections, {title:'title',data:['2','5']}]
})