【发布时间】:2021-03-25 12:53:33
【问题描述】:
我想在两个对象数组之间建立关联,但我一直坚持这一点。 说明:
我有一系列不同的参考产品
const array1 = [
{name: peanuts, referenceKey: 0},
{name: almond, referenceKey: 1},
{name: nuts, referenceKey: 2},
{name: cream, referenceKey: 3}
]
我有另一个开放参考产品表,除了每个开放产品的特定密钥外,还有一个到期日期和与 array1 中的参考密钥相同的参考密钥
const array2 = [
{name: peanuts, expirationDate: "30d", referenceKey:0, otherKey: 42},
{name: peanuts, expirationDate: "20d", referenceKey:0, otherKey: 43},
{name: peanuts, expirationDate: "15h", referenceKey:0, otherKey: 44},
{name: almond, expirationDate: "30d", referenceKey:1, otherKey: 45},
{name: cream, expirationDate: "1d", referenceKey: 3, otherKey: 46},
{name:cream, expirationDate: "12h", referenceKey: 3, otherKey: 47}
]
我想做的是计算打开的array2 的相同产品的数量,并基于array1 将这个数字推入一个新的array,如下所示:
const array3 = [
{name: peanuts, referenceKey: 0, opened: 3},
{name: almond, referenceKey: 1, opened: 1},
{name: nuts, referenceKey: 2, opened: 0},
{name: cream, referenceKey: 3, opened: 2}
]
我尝试使用 Reduce() 方法按名称重新组合 array2,如下所示:
const groupByName = (products, name) => {
return products.reduce((acc, obj) => {
var key = obj[name];
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj);
return acc
}, [])
};
const groupByName = groupByReference(array2, "name")
console.log(groupByName)
groupByName 的输出:
[
[peanuts:
[
{name: peanuts, expirationDate: "30d", referenceKey: 0, otherKey: 42},
{name: peanuts, expirationDate: "20d", referenceKey:0, otherKey: 43},
{name: peanuts, expirationDate: "15h", referenceKey:0, otherKey: 44},
],
cream: [
{name: cream, expirationDate: "1d", referenceKey: 3, otherKey: 46 },
{name: cream, expirationDate: "12h", referenceKey: 3, otherKey: 47}
],
almond: [
{name: almond, expirationDate: "30d", referenceKey:1, otherKey: 45},
]
]
然后我尝试检索每个数组的长度,但我不明白。我尝试使用 Map() 方法,但它不起作用。
即使我像 groupByName['peanuts'] 这样指定索引,console.log() 也会返回正确的数组。但是使用groupByName['peanuts'].length 不起作用。
【问题讨论】:
-
可能只是问题的拼写错误,但要指出的是,如果值不是变量,
name: cream是语法错误。如果它是文字,那么您忘记在所有这些地方加上引号。
标签: javascript arrays sorting multidimensional-array associative-array