javascript - Using template literal for dynamic property in ReactJS -


my failed attempt:

temp.map((obj,i) => ({      obj[`person${++i}`] = obj.person.name }) 

i want produce this

[{id:324, person1:'mike'},{id:23, person2:'jane'}]  

but i'm stuck on making property dynamic concatenation using template literal string.

issue code is, directly returning data using

() => ({....})

and there using obj[...] not valid key.


map return new array store result in new variable, if want modify same array better use foreach.

check snippet:

let arr = [{id: 10, name: 'a'}, {id: 20, name: 'b'}];    let newarr = arr.map((el,i) => ({      id: el.id,      [`name${i+1}`]: el.name  }));    console.log('new array', newarr);

modifying same data using foreach:

let arr = [{id: 10, name: 'a'}, {id: 20, name: 'b'}];    arr.foreach((el,i) => {     el[`person${i+1}`] = el.name;  })    console.log('modified array', arr);


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -