pageNotfoUnd
pageNotfoUnd

Reputation: 666

How can I setState for the nested array and objects?

I need to save a data in this format:

categoryselect: 0: {
  {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
  }
},: 1: {
  {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
  }
},

Whenever I click new category I need to create a new object under categoryselect and if I click add new question I need to create an object under categoryselect[0].qustion[]. I tried like this but it doesn’t seem to do what I want:

this.setState({
  categoryselect: [
    this.state.categoryselect,
    {
      question: [
        ...this.state.categoryselect.question,
        addQuestion
      ]
    }
  ],
});

Upvotes: 0

Views: 119

Answers (2)

trincot
trincot

Reputation: 350127

Looks like categoryselect should really be an array, like this:

categoryselect: [{
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
}, {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
}]

This will use the same numerical keys, but on top of that you'll have a length property and array methods.

When a category needs to be added, just do:

this.setState({
    categoryselect: [...this.state.categoryselect, {
        question: [],
        cateName: 'checkbox'
        name: '',
        status: 1
    }]
});

... to add a question to the first category, do:

this.setState({
    categoryselect: Array.from(this.state.categoryselect, (cat, i) =>
        i != this.state.categoryselect.length-1 ? cat 
             : {...cat, ...{question: [...cat.question, addQuestion]}}
    ) 
});

Upvotes: 1

onkar.v
onkar.v

Reputation: 135

To create the object that you want you can use the following script -

 categoryselect = {
  0: {
   {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
   }
  },
  1: {
   {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
   }
  }
 }

var allCategories = categorySelect[Object.keys(categorySelect).length] = {
 question:[...this.state.categoryselect.question,
    addQuestion],
 cateName: 'checkbox'
 name: '',
 status: 1
}

this.setState({
 categoryselect: allCategories
});

Upvotes: 0

Related Questions