我需要从现有对象创建新的数据对象。
我有一个如下所示的对象:
var peopleObject = {
"123": { id: 123, name: "dave", age: 23 },
"456": { id: 456, name: "chris", age: 23 }
};
重建此对象后,我需要:
var peopleByNames = {
"dave": 123,
"chris": 456
};
答案 0 :(得分:2)
您可以使用Object.values
从对象中获取值列表,然后根据这些值的id
和name
填充对象。
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;}