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

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个回答

13

您可以使用Object.values()来检索值,然后使用array.reduce()来组合一个新的对象:

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'
];

let result = customers.map(obj => 
    Object.values(obj).reduce((acc, cur, i) => { 
       acc[newKeys[i]] = cur; 
       return acc; }, {}));

console.log(result);


4
我强烈建议使用键替换映射而不是简单的新键列表,因为后者强烈依赖于客户对象的键顺序。
如果客户对象满足1:1键映射,请采用类似于此方法的方法,该方法通过减少每个元组持有旧键和新键的关键元组列表来创建一个新的客户对象并将客户对象列表映射到一个新的客户对象。

function createNewCustomerFromOldOneViaBoundConfig(customer) {
  return Object.entries(this).reduce((newCustomer, [key, newKey]) => {

    newCustomer[newKey] = customer[key];
    return newCustomer;

  }, {});
};


const customerKeyReplacementMap = {
  customer_name: 'firstname',
  customer_age: 'age',
  customer_weapon: 'weapon',
  customer_email: 'email',
  customer_city: 'city'
};

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'

}].map(createNewCustomerFromOldOneViaBoundConfig, customerKeyReplacementMap);


console.log('customers : ', customers);
.as-console-wrapper { min-height: 100%!important; top: 0; }

只要至少有一个客户对象违反了其键的严格1:1映射,就必须改变从过时的对应项创建和更改新客户对象的方法。

这种情况还证明了基于替换键列表的任何方法都仅限于单个客户对象键顺序(和结构)的一种类型...

function createNewCustomerFromOldOneAndMutateKeysViaBoundConfig(oldCustomer) {
  return Object.entries(this).reduce((customer, [oldKey, key]) => {

    customer[key] = customer[oldKey];
    delete customer[oldKey];

    return customer;

  }, Object.assign({}, oldCustomer));
};


const customerKeyReplacementMap = { 
  customer_name: 'firstname',
  customer_age: 'age',
  customer_weapon: 'weapon',
  customer_email: 'email',
  customer_city: 'city'
};

const customers = [{

  additional_key_1: 'FOO',

  customer_name: 'Negan', 
  customer_age: 45,
  
  additional_key_2: 'BAR',

  customer_weapon: 'Bat',
  customer_email: 'negan@sanctuary.com',
  customer_city: 'Washington' 
}, {
  additional_key_1: 'BAZ',

  customer_name: 'Daryl', 
  customer_age: 41,

  additional_key_2: 'BIZ',

  customer_weapon: 'Crossbow',
  customer_email: 'daryl.dixon@kickass.com',
  customer_city: 'Atlanta' 
}, {
  additional_key_1: 'FOOBAR',

  customer_name: 'Rick', 
  customer_age: 45,

  additional_key_2: 'BAZBIZ',

  customer_weapon: 'Magnum 357',
  customer_email: 'rick@alexandria.com',
  customer_city: 'King County'

}].map(
  createNewCustomerFromOldOneAndMutateKeysViaBoundConfig,
  customerKeyReplacementMap
);


console.log('customers : ', customers);
.as-console-wrapper { min-height: 100%!important; top: 0; }


3
你可以创建一个简单的映射表,这样键(keys)的顺序就不重要了。

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'
  },
]

var updated = customers.map(customer => {
  const {
    customer_name,
    customer_age,
    customer_weapon,
    customer_email,
    customer_city
  } = customer;

  return {
    firstname: customer_name,
    age: customer_age,
    weapon: customer_weapon,
    email: customer_email,
    city: customer_city
  }
});

console.log(updated);


3

您可以遍历对象,然后通过newKeys中的键更改每个属性的keys

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'
]

for (let i = 0; i < customers.length; i++) {
     let customer = customers[i];
     let j = 0;
     for(let p in customer){
          customer[newKeys[j++]] = customer[p];
          delete customer[p];
     }
}

console.log(customers);


3
你可以尝试使用for...offor...in循环:

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'
]
for(var o of customers){
  var index = 0;
  for(var k in o){
    delete Object.assign(o, {[newKeys[index]]: o[k] })[k];
    index++;
  }
}
console.log(customers);


3

遍历客户数组,对于该数组中的每个对象,迭代其键并使用这些键添加值到一个新对象中,并重新命名属性名称。这样您还可以避免修改原始对象。

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' ];

const res = customers.map(obj => {
  const newObj = {};
  Object.keys(obj).forEach((k, i) => newObj[newKeys[i]] = obj[k]);
  return newObj;
});

console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }

更好的方法是将newKeys定义为一个对象,将旧键映射到新键。这样,您就不必依赖于对象中键的顺序。
只需将newKeys更改为以下所示的对象即可实现此目的:
const newKeys = { 
  customer_name: 'firstname', 
  customer_age: 'age', 
  customer_weapon: 'weapon',
  customer_email: 'email',
  customer_city: 'city'
};

并将上述代码片段中的 .map() 方法中的代码更改为

const res = customers.map(obj => {
  const newObj = {};
  Object.keys(obj).forEach(k => newObj[newKeys[k]] = obj[k]);
  return newObj;
});

1
@Milos...在我看来,这应该是被接受的答案,因为Yousaf的答案表明了任何仅基于简单键替换列表而不是任何形式的键替换映射的方法的缺点。 - Peter Seliger

3

也可以用这种方法来实现。

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'
]

let newArr = []

customers.map(c => {
    let obj = {}
    Object.values(c).map((v,i)=>{
        obj[newKeys[i]] = v;
    })
    newArr.push(obj)
})

console.log(newArr)

2

使用重命名的解构

const update = (arr) =>
  arr.map(
    ({
      customer_name: firstname,
      customer_age: age,
      customer_weapon: weapon,
      customer_email: email,
      customer_city: city,
    }) => ({
      firstname,
      age,
      weapon,
      email,
      city,
    })
  );

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"];

console.log(update(customers));


2

两个步骤:

  1. 创建一个新的键,并将值从现有键复制
  2. 删除你刚才从中复制了值的那个键

工作示例:

let myCustomer = {
  customer_name: 'Negan', 
  customer_age: 45 
}

myCustomer.firstname = myCustomer.customer_name;
myCustomer.age = myCustomer.customer_age;

delete myCustomer.customer_name;
delete myCustomer.customer_age;

console.log(myCustomer);


1

另一种选项是在字符串化的 customers 中查找属性名称时使用 replace,然后将其解析回 JSON:

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 = [
   {from: 'customer_name', to:'firstname'},
   {from: 'customer_age', to:'age'},
   {from: 'customer_weapon', to:'weapon'},
   {from: 'customer_email', to:'email'},
   {from: 'customer_city', to:'city'}
]


let str = JSON.stringify(customers);

newKeys.forEach(o=>str = str.replace(new RegExp(o.from, 'g'), o.to));

console.log(JSON.parse(str));


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