簡體   English   中英

從對象數組內的數組返回唯一的數組值

[英]Return unique array values from an array inside an array of objects

我找不到類似的問題,我有點卡住了。 我有以下 JSON 數組:

[
    {
        "Name": "element1",
        "Attributes": ["1", "2"]
    },

    {
        "Name": "element2",
        "Attributes": ["1","3" ]
    },
    {
        "Name": "element3",
        "Attributes": []
    }
]

我試圖在“屬性”屬性中創建一個包含所有唯一元素的數組,但是我在遍歷每個對象,然后遍歷數組元素以返回唯一值時遇到問題。 我正在嘗試使用 filter() 或 map() 來做到這一點。

編輯:我想要一個唯一元素的數組,所以:[1,2,3]。

你可以用幾個 Array 方法來做到這一點。 例如:

 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)

您可以使用Array#reduceArray#filter方法

 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 }, []) );


帶有ES6 箭頭功能

 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), []) );

如果lodash是一個選項,你可以很容易地得到你想要的:

> _.chain(foo).map('Attributes').flatten().uniq().value()
["1", "2", "3"]
var uniqueArr = [];

var arr = [
    {
        "Name": "element1",
        "Attributes": ["1", "2"]
    },

    {
        "Name": "element2",
        "Attributes": ["1","3" ]
    },
    {
        "Name": "element3",
        "Attributes": []
    }
];

arr.forEach(function(obj) {
   var attr = obj.Attributes;
   attr.forEach(function(val){
       if (uniqueArray.indexOf(val) < 0) {
           uniqueArray.push(val)
       }
   });
})

你有答案可供選擇。 只是為了好玩:這個使用 es6

 "use strict"; let uniqueAttr = []; const obj = [ { "Name": "element1", "Attributes": ["1", "2"] }, { "Name": "element2", "Attributes": ["1","3" ] }, { "Name": "element3", "Attributes": [] } ]; obj.forEach( element => element.Attributes.forEach( attr => uniqueAttr.indexOf(attr) < 0 && uniqueAttr.push(attr) ) ); document.querySelector("#result").textContent = uniqueAttr;
 <pre id="result"></pre>

試試這個,它將有助於解決這個問題。

 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>

在 ES6/ES2015 中,您可以使用Set擴展運算符

 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);

說明(由內而外):

  • input.map(item => item.Attributes)產生一個 Attributes 數組
  • [].concat(...)將數組展平,即生成一個包含所有 Attributes 值(包括重復項)的數組
  • new Set()從數組中生成一個 Set,即只存儲唯一的 Attribute 值
  • [...]從 Set 的值生成一個數組,即生成一個包含所有唯一 Attribute 值的數組

建立在@dfsq 答案之上,您可以用一個flatMap替換兩個mapreduce

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM