Return unique array values from an array inside an array of objects

后端 未结 8 2059
逝去的感伤
逝去的感伤 2021-01-14 16:25

I can\'t find a similar question and I\'m a bit stuck. I have the following JSON array:

[
    {
        \"Name\": \"element1\",
        \"Attributes\": [\"1\         


        
8条回答
  •  悲&欢浪女
    2021-01-14 17:13

    You can use Array#reduce and Array#filter methods

    var data = [{
        "Name": "element1",
        "Attributes": ["1", "2"]
      },
    
      {
        "Name": "element2",
        "Attributes": ["1", "3"]
      }, {
        "Name": "element3",
        "Attributes": []
      }
    ]
    
    console.log(
      // iterate over array elements
      data.reduce(function(arr, ele) {
        // push the unique values to array
        [].push.apply(arr,
          // filter out unique value
          ele.Attributes.filter(function(v) {
            // check element present in array
            return arr.indexOf(v) == -1;
          })
        );
        // return the unique array
        return arr;
        // set initial argument as an empty array
      }, [])
    );


    With ES6 arrow function

     var data = [{
         "Name": "element1",
         "Attributes": ["1", "2"]
       },
    
       {
         "Name": "element2",
         "Attributes": ["1", "3"]
       }, {
         "Name": "element3",
         "Attributes": []
       }
     ]
    
     console.log(
       data.reduce((arr, ele) => ([].push.apply(arr, ele.Attributes.filter((v) => arr.indexOf(v) == -1)), arr), [])
     );

提交回复
热议问题