如何从对象数据创建新的对象名称?

时间:2018-05-30 15:59:22

标签: javascript

我需要从现有对象创建新的数据对象。

我有一个如下所示的对象:

var peopleObject = {
    "123": { id: 123, name: "dave", age: 23 },
    "456": { id: 456, name: "chris", age: 23 }
};

重建此对象后,我需要:

var peopleByNames = {
    "dave": 123,
    "chris": 456
};

4 个答案:

答案 0 :(得分:2)

您可以使用Object.values从对象中获取值列表,然后根据这些值的idname填充对象。

var peopleObject = {
    "123": { id: 123, name: "dave", age: 23 },
    "456": { id: 456, name: "chris", age: 23 }
};


var peopleByNames = Object.values(peopleObject).reduce(function(obj, value){
  obj[value.name] = value.id;
  return obj;
}, {});


console.log(peopleByNames);

答案 1 :(得分:0)

let reconstructed = Object.values(peopleObject)
  .reduce((acc, x) => (acc[x.name] = x.id, acc), {});

基本上是单行。

答案 2 :(得分:0)

使用Object.values将原始对象转换为数组。使用map和spread运算符来循环数组元素。使用Object.assign制作新对象。

var peopleObject = {
   "123": { id: 123, name: "dave", age: 23 },
   "456": { id: 456, name: "chris", age: 23 }
};

var peopleByNames = Object.assign(...Object.values(peopleObject).map(({id,name}) => ({[name]: id})));

console.log(peopleByNames);

答案 3 :(得分:0)

您还可以使用Object.entries()reduce()Object.assign()来获取所需的结果。

<强>样本

var peopleObject = {
    "123": { id: 123, name: "dave", age: 23 },
    "456": { id: 456, name: "chris", age: 23 }
};

let result =Object.entries(peopleObject).reduce((r,v)=>Object.assign(r,{[v[1].name]:v[0]}),{});

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