gaurav oberoi
gaurav oberoi

Reputation: 463

Adding key in spread operator inside a loop

I have a state like:

this.state = {
  questionListData: [
    {
      id: 1,
      question: "Who was the first man to step on Moon?",
      options: [
        {
          opt: "Abdul Kalam"
        },
        {
          opt: "Albert Einstein"
        },
        {
          opt: "Sheldon Cooper"
        },
        {
          opt: "Salman Khan"
        }
      ]
    },
    {
      id: 2,
      question: "Who was the Second man to step on Moon?",
      options: [
        {
          opt: "Abdul Kalam2"
        },
        {
          opt: "Albert Einstein2"
        },
        {
          opt: "Sheldon Cooper2"
        },
        {
          opt: "Salman Khan2"
        }
      ]
    },
    {
      id: 1,
      question: "Who was the Third man to step on Moon?",
      options: [
        {
          opt: "Abdul Kalam3"
        },
        {
          opt: "Albert Einstein3"
        },
        {
          opt: "Sheldon Cooper3"
        },
        {
          opt: "Salman Khan3"
        }
      ]
    },
    {
      question: "Who was the Fourth man to step on Moon?",
      options: [
        {
          opt: "Abdul Kalam"
        },
        {
          opt: "Albert Einstein"
        },
        {
          opt: "Sheldon Cooper"
        },
        {
          opt: "Salman Khan"
        }
      ]
    }
  ]
};

I am dynamically adding to this list of questions under the questionListData array. While adding, id is not generated as it is user defined. So i want to automatically add an id if it is not there. for that i had done this:

this.state.questionListData.map((r,u)=>{

        console.log('new r',r)

        if(!this.state.questionListData[u].id){alert('!r.id')
       this.setState({...this.state.questionListData[u], id:u+1 })
        }
    })

But if I do this, id is not added in that perticular index of the questionListData array, but outside it, like so:

questionListData:[
    "id":4
    {"id":1,
         "question":"Who was the first man to step on Moon?",
         "options":[
            {"opt":"Abdul Kalam"},
        {"opt":"Albert Einstein"},
        {"opt":"Sheldon Cooper"},
        {"opt":"Salman Khan"}
          ]

        }

]

Please help me with the correct syntax of spread operator to add the id to that pwrticular index inside this.setState. Thanks.

Upvotes: 0

Views: 46

Answers (2)

Yes because you're adding id in your state and not in your list object in your state.

const newList = this.state.questionListData.map((obj, idx) => {
  if(!obj.id){
    obj.id = idx + 1;
  }
  return obj;
});
this.setState({ questionListData: newList });

Upvotes: 1

Clarity
Clarity

Reputation: 10873

You can do it like this:

const newList = this.state.questionListData.map((item, index) => {
  if (!item.id) {
    return {
      ...item,
      id: index + 1
    }
  }
  return item;
})

this.setState({questionListData: newList});

Upvotes: 0

Related Questions