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}]
1
  • What have you tried to convert this? Commented Sep 25, 2019 at 15:01

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.