我正在尝试创建一个像这样的对象:
type: "asset", value: { long: 1.45, short: 1.67, extendedLong: 2.67 }
从这里:
[{percent: 1.45, type: long, sector: asset}, {percent: 1.67, type: short, sector: asset}, {percent: 2.67, type: extendedLong, sector: asset}
我尝试了一种在开始时维护一个空对象的方法。我正在做这样的事情:
if (!object[asset]) {
object[asset] = { long: 1.45 }
}
else object[asset] = { short: 1.67}
但是那没有用。有人可以帮忙吗?
答案 0 :(得分:3)
您可以映射新对象并将所有对象分配给一个对象。
var array = [{ percent: 1.45, type: 'long', sector: 'asset' }, { percent: 1.67, type: 'short', sector: 'asset' }, { percent: 2.67, type: 'extendedLong', sector: 'asset'}],
result = Object.assign(...array.map(({ percent, type }) => ({ [type]: percent })));
console.log(result);
对于更深层的嵌套对象,您需要一种不同的方法,因为使用嵌套对象进行分配时,该对象会删除珍贵保存的嵌套对象。相反,您可以减少数组并保持所需结果的结构。
var array = [{ percent: 1.45, type: 'long', sector: 'asset' }, { percent: 1.67, type: 'short', sector: 'asset' }, { percent: 2.67, type: 'extendedLong', sector: 'asset' }, { percent: 1.45, type: 'long', sector: 'Convertible' }, { percent: 1.67, type: 'short', sector: 'Convertible' }, { percent: 2.67, type: 'extendedLong', sector: 'Convertible' }],
result = array.reduce((o, { percent, type, sector }) => {
o[sector] = o[sector] || {};
o[sector][type] = percent;
return o;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }