我尝试使用下划线来过滤掉对象的某些属性。以下代码的开头按预期工作,但.pick
不起作用。我的目标是将返回对象的属性限制为.pick
方法中列出的字符串。
var result = _.chain(data)
.each(function(item) {
item.answers = [];
_.each(data, function(object) {
if (item.id === object.id) {
item.answers.push({
id: object.answer_id,
email: object.answer_email,
date: object.answer_date
});
}
});
item = _.pick(item,
'id',
'owner_id',
'url',
'enabled',
'review_date',
'answers'
);
})
.uniq(function(item) {
return item.id;
})
.value();
我开始使用的数组'数据',如下所示:
[
{
id: '8ffdf27b-5a90-478a-b263-dhhdhdhhdhd',
answer_date: Fri Oct 30 2015 14:35:07 GMT-0400 (EDT),
answer_id: 1,
answer_email: 'test@example.com',
owner_id: 5,
url: 'media/5-4a3640ac-ec13-fhhfh-ac0a-fhjhdhhdhd.jpg',
enabled: false,
review_date: Sun Nov 01 2015 13:57:32 GMT-0500 (EST)
}, ...
]
返回的数组'应该'看起来像这样:
[
{
id: '8ffdf27b-5a90-478a-b263-dhhdhdhhdhd',
owner_id: 5,
url: 'media/5-4a3640ac-ec13-fhhfh-ac0a-fhjhdhhdhd.jpg',
enabled: false,
review_date: Sun Nov 01 2015 13:57:32 GMT-0500 (EST),
answers: [{...}, {...}]
}, ...
]
但目前看起来像这样:
[
{
id: '8ffdf27b-5a90-478a-b263-dhhdhdhhdhd',
answer_date: Fri Oct 30 2015 14:35:07 GMT-0400 (EDT),
answer_id: 1,
answer_email: 'test@example.com',
owner_id: 5,
url: 'media/5-4a3640ac-ec13-fhhfh-ac0a-fhjhdhhdhd.jpg',
enabled: false,
review_date: Sun Nov 01 2015 13:57:32 GMT-0500 (EST),
answers: [{...}, {...}]
}, ...
]
答案 0 :(得分:2)
您应该使用map()
代替each()
来更改数组(请注意,您必须在地图函数中返回修改后的项目):
var result = _.chain(data)
.map(function (item) {
item.answers = [];
_.each(data, function (object) {
if (item.id === object.id) {
item.answers.push({
id: object.answer_id,
email: object.answer_email,
date: object.answer_date
});
}
});
item = _.pick(item,
'id',
'owner_id',
'url',
'enabled',
'review_date',
'answers'
);
return item;
})
.uniq(function (item) {
return item.id;
})
.value();