gpt4 book ai didi

javascript - underscore.js - 从对象列表中嵌入的对象创建唯一项目数组

转载 作者:可可西里 更新时间:2023-11-01 10:27:09 25 4
gpt4 key购买 nike

我一直在尝试使用 underscore.jsMeteor我正在处理的项目,但似乎无法弄清楚如何转换一组对象。

对象看起来像这样(大约有 15k,但它们看起来都像这两个):

 [{
"_id": "a_0011223344",
"taggedUsers": [{
"id": 1122244453,
"username": "john123"
}],
"field": "ABC"
}, {
"_id": "a_0011223345",
"taggedUsers": [{
"id": 1122244454,
"username": "bill123"
}, {
"id": 1122244455,
"username": "jim123"
}],
"field": "ABC"
}]

每个对象都可以有一个或多个"taggedUsers" 对象,我需要一个唯一的"taggedUsers.username" 字段列表。 Meteor 不支持 mongoDB 的 distinct函数,所以我尝试改用 underscore.js(根据我阅读的内容和 this post 中的推荐)。

在我的服务器端控制台 db.myCollection.distinct("taggedUsers.username") 返回所需的结果 ["john123", "bill123", "jim123"],但我无法在 underscore.js 中复制它。

我一直在尝试 _.each_.map_.pluck_.uniq 的组合,但是没有成功。我认为它可能与嵌入对象中的字段有关,但我不确定。

理想情况下,我想返回一个如下所示的对象数组:

[{
"id": 1122244453,
"username": "john123",
"field": "ABC"
}, {
"id": 1122244454,
"username": "bill123",
"field": "ABC"
}, {
"id": 1122244455,
"username": "jim123",
"field": "DEF"
}]
只有 taggedUsers.usernametaggedUsers.idfield 字段,并删除了所有重复项,但如果我也能获取 taggedUsers.usernames 的数组,就像我在 db.colleciton.distinct() 函数中一样。

最终,如果知道如何获取基本数组、唯一对象数组(或者甚至可能如何在模板中获取 db.collection.distinct() 的结果)会很好helper),但任何帮助或正确方向的观点将不胜感激!

最佳答案

根据我们的谈话,听起来最好通过方法调用在服务器上计算它。出于教育目的,以下是使用下划线的方法:

// Get an array of docs somehow
var docs = Collection.find().fetch();

var taggedUsers = _.chain(docs)
.map(function(d) {
// Copy the 'field' to each of the tagged users within a doc
_.each(d.taggedUsers, function(user) {
user.field = d.field;
});
return d;
})
.pluck('taggedUsers') // Extract only the tagged users arrays
.flatten() // Flatten them into a single array
.value();

// taggedUsers could look something like:
// [ { id: 1122244453, username: 'john123', field: 'ABC' },
// { id: 1122244454, username: 'bill123', field: 'ABC' },
// { id: 1122244455, username: 'jim123', field: 'ABC' },
// { id: 1122244453, username: 'john123', field: 'ABC' } ]

// Compute a unique lists of tagged users, where the docs are unique by id
var utu = _.uniq(taggedUsers, false, function(user) {return user.id;});

关于javascript - underscore.js - 从对象列表中嵌入的对象创建唯一项目数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32855350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com