0

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

1
  • 1
    1) fix formatting 2) this is just a simple property access? Commented Jun 5, 2018 at 17:58

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

That’s great for adding objects. Do I just use state.sections.data.push to add elements to the data array?
@DCR sections is an array of object, so to add elements in data of any object in section you need to do : state.sections[index].data.push(element)
1

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.

Comments

1

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']}]
})

2 Comments

We need to use setState to change state
@DCR are you want to use react setState?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.