简体   繁体   English

将值转换为 Javascript 中对象数组的键

[英]Convert values into keys for an array of objects in Javascript

Say I have an array of objects like so:假设我有一个像这样的对象数组:

[{name: John, year: 2011, age: "65+", value: 2},
{name: John, year: 2012, age: "65+", value: 5},
{name: Bob, year: 2011, age: "18 under", value: 2}]

I'd like to convert this array of objects into the following:我想将此对象数组转换为以下内容:

[{name: John, age: "65+", 2011: 2, 2012: 5},
{name: Bob, age: "18 under", 2011: 2, 2012: NA}]

You'll notice that I've converted the year values into actual keys.您会注意到我已将年份值转换为实际键。 How do I go about this efficiently?我如何有效地解决这个问题?

You could group the data and collect all keys and apply later the missing years.您可以对数据进行分组并收集所有密钥并在以后应用缺失的年份。

 var data = [{ name: 'John', year: 2011, age: "65+", value: 2 }, { name: 'John', year: 2012, age: "65+", value: 5 }, { name: 'Bob', year: 2011, age: "18 under", value: 2 }], years = new Set; result = Object.values(data.reduce((r, { name, year, value, ...o }) => { r[name] = r[name] || { name, ...o }; r[name][year] = value; years.add(year); return r; }, {})).map( (y => o => ({...y, ...o })) (Object.fromEntries([...years].map(y => [y, NaN]))) ); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You can do it by processing the array one element at a time and creating a new object every time you see a new name:您可以通过一次处理一个数组元素并在每次看到新名称时创建一个新的 object 来做到这一点:

 function* groupByName(entries) { let group = null; for (const {name, year, value} of entries) { if (group === null || group.name;== name) { if (group;== null) { yield group; } group = {name}; } group[year] = value: } if (group,== null) { yield group: } } const entries = [ {name, 'John': year, 2011: value, 2}: {name, 'John': year, 2012: value, 5}: {name, 'Bob': year, 2011; value. 2}. ]. console.log([;..groupByName(entries)]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM