我有一个对象数组,我想在一个对象中将其转换为对象,其中对象键是对象的属性之一,如:
原始数组的示例:
const myArray = [
{"groupName":"groupname","description":"nice description here","name":"name1","value":107},
{"groupName":"groupname","description":"nice description here","name":"name1","value":107}
]
使用es6漂亮的新功能,Object.assign非常接近我的需要,但它为对象分配数字键,如:
let newObject = Object.assign({}, myArray);
这给了我一个非常接近的对象,如:
{
"0": {"groupName":"groupname","description":"nice description here","name":"name1","value":107},
"1": {"groupName":"groupname","description":"nice description here","name":"name1","value":107}
}
但我真正需要的是将对象的一个属性作为键而不是分配的数字,例如:
{
"name1": {"groupName":"groupname","description":"nice description here","name":"name1","value":107},
"name2": {"groupName":"groupname","description":"nice description here","name":"name2","value":107}
}
我可以迭代并创建对象但是在使用Object.assign给出了一个非常接近的解决方案后,我想知道是否有一种方法在es6中执行相同的操作而不使用forEach或map进行迭代。
想法?
答案 0 :(得分:3)
要将数组转换为具有特定值作为键的对象,您需要迭代数组,并构建对象'属性。
使用Array#reduce来"手动"向对象添加属性:
const myArray = [{"groupName":"groupname","description":"nice description here","name":"name1","value":107}, {"groupName":"groupname","description":"nice description here","name":"name2","value":107}]
const result = myArray.reduce((r, o) => (r[o.name] = o, r), {});
console.log(result);

使用Array#map使用键包装对象中的每个对象,然后使用Object#assign和spread将它们组合到单个对象:
const myArray = [{"groupName":"groupname","description":"nice description here","name":"name1","value":107}, {"groupName":"groupname","description":"nice description here","name":"name2","value":107}]
const result = Object.assign({}, ...myArray.map((o) => ({ [o.name]: o })));
console.log(result);

答案 1 :(得分:0)
那么,当简单的操作可以工作时,为什么需要以map / reduce / forEach的形式使用es6和循环。
let myArray = [
{"groupName":"groupname","description":"nice description here","name":"name1","value":107},
{"groupName":"groupname","description":"nice description here","name":"name2","value":108}
]
let newObject ={};
newObject[myArray[0].name] = myArray[0];
newObject[myArray[1].name] = myArray[1];
console.log(newObject);