我有一個對象的數組數:Lodash得到重複使用對象本身
[ {
"username": "user1",
"profile_picture": "TESTjpg",
"id": "123123",
"full_name": "User 1"
}, {
"username": "user2",
"profile_picture": "TESTjpg",
"id": "43679144425",
"full_name": "User 2"
}, {
"username": "user2",
"profile_picture": "TESTjpg",
"id": "43679144425",
"full_name": "User 2"
} ]
我想:
[ {
"username": "user1",
"profile_picture": "TESTjpg",
"id": "123123",
"full_name": "User 1",
"count": 1
}, {
"username": "user2",
"profile_picture": "TESTjpg",
"id": "43679144425",
"full_name": "User 2",
"count": 2
} ]
我用lodash又名強調了這種方法,但失敗了來處理它。
var uniqueComments = _.chain(comments).uniq(function(item) { return item.from.id; }).value();
var resComment = [];
_.forEach(uniqueComments, function(unco) {
unco.count = _.find(comments, function(comment) {
return unco.id === comment.id
}).length;
resComment.push(unco);
});
結果應該在resComment
。
編輯:更新了對象數組。
你不給我們的源數據,否則我可以給你一個更短的解決方案,它看起來有點更好。但是,考慮一下:_(評論).uniq(「item.from.id」)countBy('名稱) –
我已經更新了問題@EngineerDollery – Yagiz
lodash,並強調是兩個不同的文庫,其中lodash涵蓋了大部分的下劃線方法。在相同的簽名,並提供更多更高性能的方式。 lodash不是「也被稱爲」下劃線。 – CKK