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

后端 未结 8 2047
逝去的感伤
逝去的感伤 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:01

    With ES6/ES2015 you can use Set and the spread operator:

    const input = [
        {
            "Name": "element1",
            "Attributes": ["1", "2"]
        },
    
        {
            "Name": "element2",
            "Attributes": ["1","3" ]
        },
        {
            "Name": "element3",
            "Attributes": []
        }
    ];
    
    const output = [...new Set([].concat(...input.map(item => item.Attributes)))];
    
    console.log(output);

    Explanation (from the inside out):

    • input.map(item => item.Attributes) produces an array of the Attributes arrays
    • [].concat(...) flattens the arrays, i.e. produces an array of all the Attributes values (including duplicates)
    • new Set() produces a Set from the array, i.e. stores only the unique Attribute values
    • [...] produces an array from the Set's values, i.e. produces an array of all unique Attribute values

提交回复
热议问题