[英]Merge arrays with underscore.js
在執行了一些underscore.js操作( _.map
, _.each
. _.map
, _.each
. _.pluck
和_.flatten
)之后,我得到了一個對象數組,如下所示:
var userArray = [
{id: 123456, username: "bill123", group: "ONE"},
{id: 123457, username: "joe123", group: "TWO"},
{id: 123457, username: "joe123", group: "TWO"},
{id: 123458, username: "jim123", group: "ONE"}
]
我需要創建一個新數組,刪除重復項,並計算對象出現在數組中的次數。 我能夠通過兩個單獨的underscore.js函數獲得所需的結果,但是在合並兩個結果時遇到了麻煩。
工作功能如下:
var uniqUsers = _.uniq(taggedUsers, false, function(user) {
return user.id
});
//returns array of unique objects in the same format as above
//[{id: 123457, username: "joe123", group: "TWO"},...]
var userCounts = _.countBy(taggedUsers, "id");
//returns the count for each user in the userArray in a single object
//{123456: 1, 123457: 2, 123458: 1}
返回這樣的對象數組的最佳方法是什么:
{id: 123457, username: "joe123", group: "TWO", count: 2}
我可以在_.countBy
函數中添加其他字段嗎? 還是我需要對_.map
做些事情?
任何幫助將不勝感激 ! 謝謝
您可以在userCounts
上使用map
來創建一個新數組,然后可以對其進行排序。
var userArray = [
{id: 123456, username: "bill123", group: "ONE"},
{id: 123457, username: "joe123", group: "TWO"},
{id: 123457, username: "joe123", group: "TWO"},
{id: 123458, username: "jim123", group: "ONE"}
];
var userCounts = _.countBy(userArray, "id");
var result = _.sortBy(_.map(userCounts, function(count, id) {
var user = _.findWhere(userArray, {id: Number(id)});
return _.extend({}, user, {count: count});
}), 'count');
console.log(result);
結果:
[[object Object] {
count: 1,
group: "ONE",
id: 123456,
username: "bill123"
}, [object Object] {
count: 1,
group: "ONE",
id: 123458,
username: "jim123"
}, [object Object] {
count: 2,
group: "TWO",
id: 123457,
username: "joe123"
}]
我只用兩個_.each
:
var uniquedUsersWithCount = [],
userIDToCount = {};
_.each(taggedUsers, function (user) {
if (userIDToCount[user.id] !== undefined) {
userIDToCount[user.id] += 1;
} else {
userIDToCount[user.id] = 0;
uniquedUsersWithCount.push(user);
}
});
_.each(uniquedUsersWithCount, function (user) {
var count = userIDToCount[user.id];
if (count !== undefined) {
user.count = count;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.