将值转换为Javascript中的对象数组的键
说我有一个像这样的对象数组:
[{name: John, year: 2011, value: 2},
{name: John, year: 2012, value: 5},
{name: Bob, year: 2011, value: 2}]
我想将此对象数组转换为以下内容:
[{name: John, 2011: 2, 2012: 5},
{name: Bob, 2011: 2, 2012: NA}]
您会注意到我已经将年份值转换为实际的键。我如何有效地解决这个问题?
回答如下:您可以将数据分组并收集所有密钥,然后在缺少的年份中应用。
var data = [{ name: 'John', year: 2011, value: 2 }, { name: 'John', year: 2012, value: 5 }, { name: 'Bob', year: 2011, value: 2 }],
years = new Set;
result = Object
.values(data.reduce((r, { name, year, value }) => {
r[name] = r[name] || { name };
r[name][year] = value;
years.add(year);
return r;
}, {}))
.map(o => Object.assign({}, o, ...[...years].map(y => y in o ? {} : { [y]: NaN })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
将值转换为Javascript中的对象数组的键
说我有一个像这样的对象数组:
[{name: John, year: 2011, value: 2},
{name: John, year: 2012, value: 5},
{name: Bob, year: 2011, value: 2}]
我想将此对象数组转换为以下内容:
[{name: John, 2011: 2, 2012: 5},
{name: Bob, 2011: 2, 2012: NA}]
您会注意到我已经将年份值转换为实际的键。我如何有效地解决这个问题?
回答如下:您可以将数据分组并收集所有密钥,然后在缺少的年份中应用。
var data = [{ name: 'John', year: 2011, value: 2 }, { name: 'John', year: 2012, value: 5 }, { name: 'Bob', year: 2011, value: 2 }],
years = new Set;
result = Object
.values(data.reduce((r, { name, year, value }) => {
r[name] = r[name] || { name };
r[name][year] = value;
years.add(year);
return r;
}, {}))
.map(o => Object.assign({}, o, ...[...years].map(y => y in o ? {} : { [y]: NaN })));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
发布评论