簡體   English   中英

從Javascript中的對象列表中提取對象屬性

[英]Extract object attribute from list of objects in Javascript

我從API接收到以下對象:

{
   '2012-12-12': [
       { 'id': 1234,
         'type': 'A' },
       { 'id': 1235,
         'type': 'A' },
       { 'id': 1236,
         'type': 'B' },
    ],
   '2012-12-13': [
       { 'id': 1237,
         'type': 'A' },
       { 'id': 1238,
         'type': 'C' },
       { 'id': 1239,
         'type': 'B' },
    ]
}

然后我想要另一個名為Array types的變量,它將保存每個對象的type屬性的每個可能值。 在這種情況下,它將是:

types = ['A', 'B', 'C']

我試圖以功能方式完成它(我使用的是underscore.js),但我無法找到一種方法。 現在我正在使用

types = [];
_.each(response, function(arr1, key1) {
    _.each(arr1, function(arr2, key2) {
        types.push(arr2.type);
    });
});
types = _.uniq(types);

但那非常難看。 你能幫我找出更好的編寫代碼的方法嗎?

謝謝!

這應該工作:

types = _.chain(input) // enable chaining
  .values()            // object to array
  .flatten()           // 2D array to 1D array
  .pluck("type")       // pick one property from each element
  .uniq()              // only the unique values
  .value()             // get an unwrapped array

小提琴: http//jsfiddle.net/NFSfs/

當然,如果您願意,可以刪除所有空格:

types = _.chain(input).values().flatten().pluck("type").uniq().value()

或沒有鏈接:

types = _.uniq(_.pluck(_.flatten(_.values(input)),"type"));

flatten似乎在對象上工作 ,即使文檔明確指出它不應該 如果您希望對實現進行編碼,則可以省略對values的調用,但我不建議這樣做。 實施可能會在一天內發生變化,使您的代碼神秘地破裂。

如果您只想要更短的代碼,可以將對象展平為單個數組,然后映射該數組。

var types = _.unique(_.map(_.flatten(_.toArray(response)), function(arr) {
    return arr.type;
}));

這是另一個版本。 主要是出於好奇心的緣故。

var types = _.unique(_.pluck(_.reduce(response, _.bind(Function.apply, [].concat), []), "type"));

這是另一個。

var types = _.unique(_.reduce(response, function(acc, arr) {
    return acc.concat(_.pluck(arr,"type"));
}, []));

而另一個。

var types = _.unique(_.pluck([].concat.apply([], _.toArray(response)), "type"))

暫無
暫無

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

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