简体   繁体   English

根据动态传递的属性从对象数组中获取唯一值

[英]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.

相关问题 从对象数组派生唯一属性值数组 - derive array of unique property values from an array of objects 根据 Javascript 中的属性值从数组的 object 中获取唯一对象 - Getting unique objects from object of array based on property value in Javascript VueJS根据监视键从对象数组中获取唯一值 - VueJS get unique values from array of objects based on key in watch 根据两个键从对象数组中获取唯一值 - Get unique values from an array of objects based on two keys 如何根据属性匹配来自不同对象数组的值? - How to match values from different array of objects based on a property? 基于两个或多个键的对象数组和动态收集的值数组对对象进行分组 - Group objects from an array of objects based on two or more keys and from an array of dynamically collected values 需要基于相对于对象数组的数组迭代来获取属性 - Need to fetch a property based on iteration over an array with respect to array of objects 如何从对象数组中获取属性本身的所有唯一值,该属性本身就是数组 - How to get from an array of objects all unique values of a property that is an array itself 根据属性值删除对象数组中的重复项 - Removing Duplicates in Array of Objects based on Property Values 从对象数组中获取唯一值 - Get unique values from array of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM