[英]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]};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.