2 回答
TA贡献1831条经验 获得超10个赞
假设JSON是结构化的,我们可以得到fruits的值:
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;
}
}
TA贡献1806条经验 获得超8个赞
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')];
添加回答
举报