简体   繁体   English

如何将对象数组转换为具有相同值但具有修改键的对象数组?

[英]How can I convert an array of objects into an array of objects with the same values but with modified keys?

I have an array with objects and want to convert this to an array containing the same values but with different key names.我有一个包含对象的数组,并希望将其转换为包含相同值但具有不同键名的数组。 (JavaScript) (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}]

Using the Map function works perfectly here.使用 Map function 在这里完美运行。

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.这应该适用于这个问题。

I think that you may use the map method this method returns and array with the same length as the one you are mapping:我认为您可以使用map方法,该方法返回的数组长度与您要映射的数组长度相同:


 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.因此,在 map 中,您将需要的值分配给新的 object 并将 object 作为映射项返回

Just in case you prefer to modify the objects in place, you can make use of a strategy by nverba here :以防万一您更喜欢就地修改对象,您可以 在此处使用 nverba 的策略:

 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[1]是新键。 keyMap[0] is the old key. keyMap[0]是旧键。 Object.assign takes the value of the old key and places it in the new key. Object.assign获取旧键的值并将其放入新键中。 The delete keyword is confusing, but it doesn't apply to row as a whole. delete关键字令人困惑,但它不适用于整个row It's only deleting the old key.它只是删除旧密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM