计数对象数组内的数组
2021-04-19
940
假设我有一个 Object 数组,如下所示:
预期 O/P : {alpha:4, beta:8
为此,我尝试了:
const apple = [{
name: 'alpha',
details: [{
"attachment": [123, 456]
}, {
"attachment": [1454, 1992]
}]
},
{
name: 'beta',
details: [{
"attachment": ["12", 189]
}, {
"attachment": ["maggi", 1890, 2000]
}, {
"attachment": [1990, 2001, 2901]
}]
}
];
const appleDetails = [];
for (let i = 0; i < apple.length; i++) {
for (let j = 0; j < apple[i].details.length; j++) {
const {
name
} = apple[i];
const {
attachment
} = apple[i].details[j]
appleDetails.push({
name,
attachment
})
}
}
let appleData = [];
appleDetails.forEach(({
name,
attachment
}) => {
attachment.forEach((attatchId) => {
appleData.push({
name,
_id: attatchId
})
})
})
const eachAppleCount = appleData.reduce((acc, item) => {
const key = item.name
if (!acc.hasOwnProperty(key)) {
acc[key] = 0
}
acc[key] += 1
return acc
}, {})
console.log(eachAppleCount);
这给出了所需的 O/P,即: {alpha:4, beta:8
但涉及的过程太多,有没有更有效的方法,例如,通过使用:
const apple = [{
name: 'alpha',
details: [{
"attachment": [123, 456]
}, {
"attachment": [1454, 1992]
}]
}, {
name: 'beta',
details: [{
"attachment": ["12", 189]
}, {
"attachment": ["maggi", 1890, 2000]
}, {
"attachment": [1990, 2001, 2901]
}]
}];
我们可以计算每个苹果名称的值。如果有人需要任何进一步的信息,请告诉我。
2个回答
这将完成工作
const apple = [{
name: 'alpha',
details: [{
"attachment": [123, 456]
}, {
"attachment": [1454, 1992]
}]
}, {
name: 'beta',
details: [{
"attachment": ["12", 189]
}, {
"attachment": ["maggi", 1890, 2000]
}, {
"attachment": [1990, 2001, 2901]
}]
}];
const result = apple.reduce((acc, curr) => {
if (acc[curr.name] === undefined) acc[curr.name] = 0;
curr.details.forEach((d) => (acc[curr.name] += d.attachment.length));
return acc;
}, {});
console.log(result);
Lior Kaminsky
2021-04-19
尝试如下方法。
- Array.prototype.map() - map() 方法 创建一个新数组 ,该数组填充了对调用数组中每个元素调用提供的函数的结果。
-
创建新对象为
{[a.name]: values>
,其中我们在[]
内使用[a.name]
,因此a.name
中的值将被设置为对象键。 - 为了获取值,我们使用 Array.prototype.flatMap() - flatMap() 方法返回一个新数组,该数组通过将给定的回调函数应用于数组的每个元素,然后将结果展平一级而形成。
-
使用
a.details.flatMap(d => d.attachment)
获取所有附件,并使用.length
获取总计数作为值。 -
map
将以对象数组的格式返回结果。 - 使用 Array.prototype.reduce() 和 spread 语法 (...) 将对象数组合并为单个对象。
const apple = [
{ name: 'alpha', details: [{"attachment": [ 123, 456 ]}, {"attachment": [1454, 1992 ]} ]},
{name: 'beta', details: [{"attachment": [ "12", 189 ]},{"attachment": ["maggi", 1890,2000 ]}, {"attachment": [1990, 2001,2901 ]} ]}
];
// map will return result in format of array of objects
let resultArr = apple.map(a => ({[a.name]: a.details.flatMap(d => d.attachment).length }));
// use reduce with spread syntax (...) to club array of objects into single object.
let result = resultArr.reduce((i, a) => ({...a, ...i}), {});
console.log(result);
Karan
2021-04-19