根据嵌套键值对对象进行计数

时间:2019-07-24 21:29:45

标签: javascript jquery arrays json

已编辑 我有这个嵌套的json,我想搜索一个值,然后返回找到该值的整个对象,并对这些对象进行计数,然后使用map和filter重新创建该对象。我不知道该怎么做,因为我是编程方面的新手。

在示例json中,我想搜索水果的值,然后计算所有带有日期的水果的总对象数。

示例Json对象:

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'
 },
]

我希望输出结果是这样,并在搜索水果的价值后计数

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

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

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');

如果您希望数据成为数组,则将最后一行更改为此

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

答案 1 :(得分:0)

假设JSON是结构化的,我们可以获得水果的价值:

function fruitCount(sampleData) {
    var results = {};

    // sampleData is a list, so for each item
    sampleData.forEach((container) => {

        // Get the relevant data from the subfields.
        let date = container.dateCreated;
        let fruit = container.fruitData.fruit;

        // If the date has been found before, we'll reuse it.
        // If the fruit has been found before, we'll increment it.
        // If the fruit has NOT been found before, we'll insert it with a
        //     value of 1.
        if (date in results) {
            results[date][fruit] = results[date][fruit] + 1 || 1;

        // The date has not been found before, so create it.
        } else {
            results[date] = {fruit: 1};
        }
    });

    return results;
}
if (date in results) {
    results[date][fruit] = results[date][fruit] + 1 || 1;

等同于

if (date in results) {
    if (fruit in results[date]) {
        results[date][fruit]++;
    } else {
        results[date][fruit] = 1;
    }
}