簡體   English   中英

Lodash變換對象和字符串的數組混合

[英]Lodash transform array mix of objects and strings

我有一個包含對象和字符串混合的數組。 我需要將數組轉換為另一個對象數組。

輸入數組:

[
  {"text": "Address"},
  {"text": "NewTag"},
  {"text": "Tag"},
  "Address",
  "Name",
  "Profile",
  {"text": "Name"},
]

out數組應該是這樣的:

[
  {"Tag": "Address", Count: 2},
  {"Tag": "Name", Count: 2},
  {"Tag": "NewTag", Count: 1},
  {"Tag": "Profile", Count: 1},
  {"Tag": "Tag", Count: 1},
]

這是我的代碼(看起來很愚蠢):

var tags = [], tansformedTags=[];   
for (var i = 0; i < input.length; i++) {
  if (_.isObject(input[i])) {
    tags.push(input[i]['text']);
  } else {
    tags.push(input[i]);
  }
}
tags = _.countBy(tags, _.identity);
for (var property in tags) {
  if (!tags.hasOwnProperty(property)) {
    continue;
  }
  tansformedTags.push({ "Tag": property, "Count": tags[property] });
}
return _.sortByOrder(tansformedTags, 'Tag');

我想知道是否有更好,更優雅的方式來執行此操作?

您可以使用Object.create(null)創建一個哈希表,您可以在其中計算數組中的屬性,然后使用Object.keys獲取其屬性,並使用map來構建對象。

var count = Object.create(null);
myArray.forEach(function(item) {
  var prop = Object(item) === item ? item.text : item;
  count[prop] = (count[prop] || 0) + 1;
});
Object.keys(count).sort().map(function(key) {
  return {Tag: key, Count: count[key]};
});

通過使用map()countBy()

_(arr)
    .map(function(item) {
        return _.get(item, 'text', item);
    })
    .countBy()
    .map(function(value, key) {
        return { Text: key, Count: value };
    })
    .value();

暫無
暫無

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

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