使用像这样的对象数组:
const data = [
{count: 400, value: "Car Wash Drops"},
{count: 48, value: "Personal/Seeding"},
{count: 48, value: "Personal/Seeding"},
];
我想映射
到一个带有重复值附加标识符的数组:
const expected = [
["Car Wash Drops", 400],
["Personal/Seeding (1)", 48],
["Personal/Seeding (2)", 48],
];
到目前为止,我有一个映射函数来相应地映射值,但我不确定如何继续为重复项附加标识符。
data.map(d => [`${d.value}`, d.count]);
结果:
[
["Car Wash Drops", 400],
["Personal/Seeding", 48],
["Personal/Seeding", 48],
]
我也使用了索引,但它在每个值上都添加了索引:
data.map((d, i) => [`${d.value} ${i}`, d.count]);
结果:
[
["Car Wash Drops (0)", 400],
["Personal/Seeding (1)", 48],
["Personal/Seeding (2)", 48],
]
最佳答案
使用您的方法,您可以在 map 内部使用 filter()
来检查原始数组中有多少元素与当前分析的元素具有相同的值,使用此条件您可以选择要作为新值返回:
const data = [
{count: 400, value: "Car Wash Drops"},
{count: 48, value: "Personal/Seeding"},
{count: 48, value: "Personal/Seeding"},
];
let res = data.map((x, idx) =>
{
if (data.filter(y => y.value === x.value).length > 1)
return [`${x.value} (${idx})`, x.count];
else
return [`${x.value}`, x.count];
});
console.log(res);
如果我们使用 some()
而不是 filter()
可以提高之前方法的性能,如下所示:
const data = [
{count: 400, value: "Car Wash Drops"},
{count: 48, value: "Personal/Seeding"},
{count: 48, value: "Personal/Seeding"},
{count: 300, value: "Operators/Management"},
{count: 48, value: "Personal/Seeding"}
];
let res = data.map((x, idx) =>
{
if (data.some((y, j) => y.value === x.value && idx !== j))
return [`${x.value} (${idx})`, x.count];
else
return [`${x.value}`, x.count];
});
console.log(res);
如果我们之前创建一个 Map 可以进一步改进带有元素出现在原始数组中的次数的计数器。像这样:
const data = [
{count: 400, value: "Car Wash Drops"},
{count: 48, value: "Personal/Seeding"},
{count: 48, value: "Personal/Seeding"},
{count: 300, value: "Operators/Management"},
{count: 48, value: "Personal/Seeding"}
];
let counters = data.reduce((res, {value}) =>
{
res.set(value, res.has(value) ? res.get(value) + 1 : 1);
return res;
}, new Map());
let res = data.map((x, idx) =>
{
return [
`${x.value}` + (counters.get(x.value) > 1 ? `(${idx})` : ""),
x.count
];
});
console.log(res);
关于javascript - 如何将对象数组映射到具有重复值标识符的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54221759/