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

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

    Try This, It'll help to solve this problem.

      var data = [{
        "Name": "element1",
        "Attributes": ["1", "2"]
      }, {
        "Name": "element2",
        "Attributes": ["1", "3"]
      }, {
        "Name": "element3",
        "Attributes": []
      }];
      var Attributes = [];
      $.each(data, function(i, e) {
        $.each(e.Attributes, function(i, e) {
          Attributes.push(parseInt(e));
        });
      });
      Attributes = $.unique(Attributes);
      alert(Attributes);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    0 讨论(0)
  • 2021-01-14 17:23

    You could do it with couple of Array methods. For example:

    var result = [
        {
            "Name": "element1",
            "Attributes": ["1", "2"]
        },
    
        {
            "Name": "element2",
            "Attributes": ["1","3" ]
        },
        {
            "Name": "element3",
            "Attributes": []
        }
    ]
    
    // map to [ ["1", "2"], ["1", "3"], [] ]
    .map(item => item.Attributes)
    
    // flatten to [ "1", "2", "1", "3" ]
    .reduce((prev, curr) => prev.concat(curr), [])
    
    // filter unique [ "1", "2", "3" ]
    .filter((item, i, arr) => arr.indexOf(item) === i)
    
    console.log(result)

    0 讨论(0)
提交回复
热议问题