[英]Fetch unique values from array of objects based on dynamically passed property
I have this scenario where I need to fetch unique values of all objects based on a dynamically passed property . 在这种情况下,我需要基于动态传递的属性获取所有对象的唯一值。 I have tried the following approach but does not seem like working. 我尝试了以下方法,但似乎无法正常工作。
var arr = [
{
id: "1",
type: "x",
source: {
val1: "3",
val2: "4",
val3: "6",
},
},
{
id: "1",
type: "x",
source: {
val1: "3",
val2: "4",
val3: "6",
},
},
{
id: "1",
type: "x",
source: {
val1: "4",
val2: "5",
val3: "6",
}
}
];
Now say I pass val1 it should give me unique values 3,4 and if I pass val2 it should give me 4,5. 现在说我通过val1,它应该给我唯一的值3,4,如果我通过val2,它应该给我4,5。 PS : I will only pass the parameter that are present inside source property. PS:我只会传递source属性中存在的参数。
Approach that I have tried: 我尝试过的方法:
calculate = (param) =>
{
let uniqueValues = Array.from(
new Set(arr.map((arr: any) => arr[param]))
);
}
看起来,您也需要source
属性。
new Set(arr.map((o: any) => o.source[param]))
You can use map
to get source values and then reduce
inuque values: 您可以使用map
获取源值,然后reduce
不规则值:
const arr = [ { id: "1", type: "x", source: { val1: "3", val2: "4", val3: "6", }, }, { id: "1", type: "x", source: { val1: "3", val2: "4", val3: "6", }, }, { id: "1", type: "x", source: { val1: "4", val2: "5", val3: "6", } } ]; function calculate(data, param) { return data.map(x => { return (x.source || {})[param]; }).reduce((acc, val) => { if (acc.indexOf(val) === -1) acc.push(val); return acc; }, []); } console.log(calculate(arr, "val1")); console.log(calculate(arr, "val2"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.