如何重命名数组内对象的键

19

我有一个像这样的对象数组:

const customers = [
  {
    customer_name: 'Negan', 
    customer_age: 45, 
    customer_weapon: 'Bat',
    customer_email: 'negan@sanctuary.com',
    customer_city: 'Washington' 
  },
  {
    customer_name: 'Daryl', 
    customer_age: 41, 
    customer_weapon: 'Crossbow',
    customer_email: 'daryl.dixon@kickass.com',
    customer_city: 'Atlanta' 
  },
  {
    customer_name: 'Rick', 
    customer_age: 45, 
    customer_weapon: 'Magnum 357',
    customer_email: 'rick@alexandria.com',
    customer_city: 'King County' 
  },
]

我希望替换对象中所有键,这些键为:

const newKeys = [
   'firstname',
   'age',
   'weapon',
   'email',
   'city'
]

如何最好地做到这一点?提供一个例子将会更好!


6
你能展示一下你尝试过的内容吗?我们的目的是帮助你纠正错误,而不是提供代码。 - jonatjano
1
请注意,基于替换键列表的任何方法都仅限于单个客户对象键顺序(和结构)。环境始终必须确保每个单独的客户对象具有相同的键创建顺序。 - Peter Seliger
11个回答

1

我编写了这段代码以满足我在对象属性名称更改方面的所有需求。

deepRenameKeys = function(array: any[], shape: Object): any[] {
    if (!array || !array.length || !shape) return;
    return array.map(item => {
        let _obj = {};
        for (const key in shape) {
            if (shape.hasOwnProperty(key)) {
                _obj[key] = shape[key].split('.').length ?
                    shape[key].split('.').reduce((a, b) => a[b], item) :
                    item[shape[key]];
            }
        }
        return _obj;
    })
}

请注意,您也可以使用点符号表示法:
const customers = [
    {
        customer_name: 'Negan',
        customer_age: 45,
        customer_weapon: {
            kind: 'Bat',
            type: 'melee'
        },
        customer_email: 'negan@sanctuary.com',
        customer_city: 'Washington'
    },
    {
        customer_name: 'Daryl',
        customer_age: 41,
        customer_weapon: {
            kind: 'Crossbow',
            type: 'range'
        },
        customer_email: 'daryl.dixon@kickass.com',
        customer_city: 'Atlanta'
    },
    {
        customer_name: 'Rick',
        customer_age: 45,
        customer_weapon: {
            kind: 'Magnum 357',
            type: 'range'
        },
        customer_email: 'rick@alexandria.com',
        customer_city: 'King County'
    }
];

const newKeys = [
    'firstname': 'customer_name',
    'age': 'customer_age',
    'weapon': 'customer_weapon.kind',
    'weaponType': 'customer_weapon.type'
    'email': 'customer_email',
    'city': 'customer_city'
];

let newData = deepRenameKeys(customers, newKeys);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接