简体   繁体   English

有没有办法以公共值作为键创建 object 并将公共对象分配为数组值?

[英]Is there a way to create object with common value as key and assigning the common objects as array values?

Let's say i have an array of four objects假设我有一个包含四个对象的数组

var data = [
   {a: 1, b: 2}, 
   {a: 2, b: 4}, 
   {a: 1, b: 6}, 
   {a: 2, b: 9}
];

And i want to create an object say Taking common value and passing it as key and assigning the value ob common objects to an array like below我想创建一个 object 说以通用值并将其作为键传递并将值 ob 通用对象分配给如下所示的数组

Const treat = {

    1:[{a:1,b:2} {a:1,b:6}],
    2:[{a:2,b:4} {a:2,b:9}]

}

Here is a version of what you want.这是您想要的版本。 You can research different array methods such as reduce to see other ways to obtain similar results.您可以研究不同的数组方法,例如reduce以查看获得类似结果的其他方法。

 var data = [{ a: 1, b: 2 }, { a: 2, b: 4 }, { a: 1, b: 6 }, { a: 2, b: 9 } ]; function sortData() { var sortedData = {}; data.forEach(sample => { // Need to check if the array for the sample has been created since we cannot "push" to "undefined". if (sortedData[sample.a]) { sortedData[sample.a].push(sample); } else { sortedData[sample.a] = [sample]; } }); return sortedData; } console.log(sortData());

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

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