1

I have an array with objects and want to convert this to an array containing the same values but with different key names. (JavaScript)

For example, an array of

[{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}]

becomes

[{identification: "Bob", years: 50, person: true}, {identification: "Jerry", years: 20, person: true}]
Saksham
  • 9,037
  • 7
  • 45
  • 73
deejay123
  • 89
  • 7

3 Answers3

3

Using the Map function works perfectly here.

const people = [
    {name: "Bob", age: 50, person: true},
    {name: "Jerry", age: 20, person: true}
];

const formatted = people.map((person) => ({
    identification: person.name,
    years: person.age,
    person: person.person
});

This should work for this problem.

0

I think that you may use the map method this method returns and array with the same length as the one you are mapping:


 const array = [{name: "Bob", age: 50, person: true}, {name: "Jerry", age: 20, person: true}];

let newKeysArray = array.map( a => { 
   let obj = { 
        identification: person.name,
        years: person.age,
        person: person.person
   };
   return obj
 } );

So inside the map you are assigning the values that you need to a new object and return the object as the mapped item.

Ricardo Gonzalez
  • 1,827
  • 1
  • 14
  • 25
0

Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here:

let rows = [
    {name: "Bob", age: 50, person: true}, 
    {name: "Jerry", age: 20, person: true}
];

let keyMaps = [
    ['name', 'identification'],
    ['age', 'years'],
];

for(let keyMap of keyMaps)
for(let row of rows)
    delete Object.assign(row, {[keyMap[1]]: row[keyMap[0]] })[keyMap[0]];

console.log(rows);

keyMap[1] is the new key. keyMap[0] is the old key. Object.assign takes the value of the old key and places it in the new key. The delete keyword is confusing, but it doesn't apply to row as a whole. It's only deleting the old key.

pwilcox
  • 5,542
  • 1
  • 19
  • 31