Home > database >  is it possible filter nested object by value of some property?(JS)
is it possible filter nested object by value of some property?(JS)

Time:11-19

I'm developing my own project with JS, python, and data from open API. Bringing data from API was not that tricky even for a newbie like me. However, I got trouble (like always) in making data into useful information for me.

below is a part of I'm having a struggle with,

AA:array(60)
[
0:{A:2016-01-01, B:12}
1:{A:2016-02-01, B:122}
2:{A:2016-03-01, B:162}
3:{A:2016-04-01, B:129}
.
.
.
n:{A:20NN-NN-NN, B:923}
]

as you can see it is an array that has many objects in it. every object has the same property key A,B A is literal which has date info, and B has some numerical value. What I want to make is create new objects which have year's information. in other words, new object's has all same month and day info and only the year is different in A. And B would be the sum of the same year's B (sorry for bad explaining I'm not good at English ngl). so above example would be like below.

newAA: array(5)
[
0:{A:2016-01-01, B:numeric value(sum of all 2016's B in above example)}
1:{A:2017-01-01, B:numeric value(sum of all 2017's B in above example)}
2:{A:2018-01-01, B:numeric value(sum of all 2018's B in above example)}
3:{A:2019-01-01, B:numeric value(sum of all 2019's B in above example)}
4:{A:2020-01-01, B:numeric value(sum of all 2020's B in above example)}
]

Honestly, This is quite tricky for me and I do not know how to handle it to make into what I want to If you have a good idea to do this, please let me know, your help will be appreciated.

thx for reading!

CodePudding user response:

Using Array#reduce, you can iterate over the array while updating a Map where the year is the key and an object is the value.

The result would be the values of this Map which is a list of grouped objects by the year containing its first A in the original array and total B:

const AA = [ {A:'2016-01-01', B:12}, {A:'2016-02-01', B:122}, {A:'2016-03-01', B:162}, {A:'2016-04-01', B:129} ];

const res = [...
  AA.reduce((map, { A, B }) => {
    const [year] = A.split('-');
    const yearRecord = map.get(year);
    if(yearRecord) yearRecord.B  = B;
    else map.set(year, { A, B })
    return map;
  }, new Map)
  .values()
];

console.log(res);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related