Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting objects based on nested key value

EDITED I have this nested json and I want to search for a value then return the whole object where this value was found and count those object and recreate the object using map and filter. I don't know what to do it since I'm kinda newbie in programming.

In the example json I want to search for values of fruits and then count all the total objects with value of those fruits with dates.

Sample Json object:

var sampleData = [
 {
   fruitData: {
     fruit: 'apple',
     price: 23
   },
   dateCreated: '2019-07-23T00:20:36.535Z'
 },
 {
   fruitData: {
     fruit: 'apple',
     price: 36 
   },
   dateCreated: '2019-07-23T00:30:32.135Z'
 },
 {
   fruitData: {
     fruit: 'apple',
     price: 36 
   },
   dateCreated: '2019-07-24T00:10:36.115Z'
 },
 {
   fruitData: {
     fruit: 'mango',
     price: 40 
   },
   dateCreated: '2019-07-24T01:25:32.835Z'
 },
]

I expect the output to be like this and count after searching for value of fruits

var filteredData= [
 {
   '07-23-2019': {
       'apple': 2
   },
   '07-24-2019': {
       'apple': 1,
       'mango': 1
   }
 }
]

Thank you for those who will help

like image 838
vashlor Avatar asked Sep 22 '26 18:09

vashlor


1 Answers

const sampleData = [
    {
        fruitData: {
            fruit: 'apple',
            price: 23
        },
        dateCreated: '07-23-2019'
    },
    {
        fruitData: {
            fruit: 'apple',
            price: 36
        },
        dateCreated: '07-23-2019'
    },
    {
        fruitData: {
            fruit: 'mango',
            price: 40
        },
        dateCreated: '07-23-2019'
    },
];


function groupData(data, key) {
    const objs = {};
    for (const obj of data) {
        objs[obj[key].fruit] = (objs[obj[key].fruit] || 0) + 1;
    }
    return objs;
}

const data = groupData(sampleData, 'fruitData');

if you want data to be an array then change the last line to this

const data = [groupData(sampleData, 'fruitData')];
like image 124
Jamal Abo Avatar answered Sep 25 '26 08:09

Jamal Abo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!