Cecilia Chan
Cecilia Chan

Reputation: 739

Using template literal for dynamic property in ReactJS

My failed attempt:

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

I want to produce something like this

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

But I'm stuck on making the property dynamic with concatenation using template literal string.

Upvotes: 0

Views: 828

Answers (3)

Mayank Shukla
Mayank Shukla

Reputation: 104379

Issue with you code is, you are directly returning the data by using

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

and there you are using obj[...] that is not a valid key.


map return the a new array so store the result in a new variable, if you want to modify the same array then better to use forEach.

Check this 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 the 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);

Upvotes: 1

Sundar Rajan Muthuraj
Sundar Rajan Muthuraj

Reputation: 117

How about this?

describe("sample test", () => {
  it("Dynamic property in ES6", () => {
    const temp = [
      { id: 324, person: { name: "mike" } },
      { id: 23, person: { name: "jane" } }
    ];
    console.log(
      temp.map((obj, i) => ({
        id: obj.id,
        [`person${i + 1}`]: obj.person.name
      }))
    );
  });
});

Output:

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

Upvotes: 0

PilotInPyjamas
PilotInPyjamas

Reputation: 987

This should do it:

var myInput = ["John", "Jane", "Steven", "Alice"];

var myOutput = myInput.map ((name, index) => {
  var out = {};
  out[`person${index}`] = name;
  return out;
}); // myOutput is [{person1:"John"}, {person2:"Jane"} ... etc.

map creates a new array rather than modifying the existing one. The values of the array are made out of the return values of the function, so if you want your values to be objects, you must create new objects and then assign your properties to them.

Upvotes: 0

Related Questions