简体   繁体   English

Javascript-从对象数组中获取数据

[英]Javascript - getting data out of array of objects

I got this sample data. 我得到了这个样本数据。

"array" : [
    {"Id" : "1", "preferred" : false}, 
    {"Id" : "1", "preferred" : true }, 
    {"Id" : "2", "preferred" : false}, 
    {"Id" : "2", "preferred" : false},]

And i would like to get out of it something like this. 我想摆脱这种情况。

"array2":[{"Id": 1, numOfTrue: 1, numOfFalse: 1},{"Id": 2, numOfTrue: 0, numOfFalse: 2}]

What i got so far is a way how to get unique id form initial array. 到目前为止,我得到的是一种如何从初始数组获取唯一ID的方法。

const unique = [...new Set(array.map(item => Id))];

Next step would be some forEach over array and comparing Id values and setting some counters for that boolean value. 下一步将是一些forEach over数组,比较ID值,并为该布尔值设置一些计数器。 So before i dive into forEach solution i would like to ask if there is another way with using . 因此,在我探讨forEach解决方案之前,我想问一问是否还有另一种使用方法。 filter() and .reduce() methods. filter().reduce()方法。

You can use reduce() to build a grouping object keyed to Id . 您可以使用reduce()构建键为Id的分组对象。 Each time you see that Id again increment the value at the appropriate key. 每次您看到Id再次在相应的键处递增该值。 In the end your array will be the Object.values() of the object: 最后,数组将是对象的Object.values()

 let array = [ {"Id" : "1", "preferred" : false}, {"Id" : "1", "preferred" : true }, {"Id" : "2", "preferred" : false}, {"Id" : "2", "preferred" : false} ] let counts = array.reduce((counts, {Id, preferred}) => { // If you haven't seen this Id yet, make a new entry if (!counts[Id]) counts[Id] = {Id, numOfTrue: 0, numOfFalse: 0} // increment the appropriate value: if (preferred) counts[Id].numOfTrue++ else counts[Id].numOfFalse++ return counts }, {}) // get the values array of the object: console.log(Object.values(counts)) 

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

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