我有这两个对象数组
todos: [
{
id: 1,
name: 'customerReport',
label: 'Report send to customer'
},
{
id: 2,
name: 'handover',
label: 'Handover (in CRM)'
},
]
和
todosMoreDetails: [
{
id: 1,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: []
},
{
id: 2,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: []
}
]
这样最终的对象数组将是两者的组合,基于对象ID,如下所示:
FinalTodos: [
{
id: 1,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: [],
name: 'customerReport',
label: 'Report send to customer'
},
{
id: 2,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: [],
name: 'handover',
label: 'Handover (in CRM)'
}
]
我尝试使用merge
mergeAll
和mergeWithKey
,但我可能遗漏了某些内容
答案 0 :(得分:8)
您可以使用中间组来实现此目标:
使用groupBy将todosMoreDetails数组转换为由todo属性ID键入的对象:
var moreDetailsById = R.groupBy(R.prop('id'), todosMoreDetails);
moreDetailsById是一个对象,其中键是id,值是todos的数组。如果id是唯一的,那么这将是一个单例数组:
{
1: [{
id: 1,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: []
}]
}
现在通过将每个待办事项合并到您从分组视图中检索的详细信息来转换todos数组:
var finalTodos = R.map(todo => R.merge(todo, moreDetailsById[todo.id][0]), todos);
另一种更详细的方式:
function mergeTodo(todo) {
var details = moreDetailsById[todo.id][0]; // this is not null safe
var finalTodo = R.merge(todo, details);
return finalTodo;
}
var moreDetailsById = R.groupBy(R.prop('id'), todosMoreDetails);
var finalTodos = todos.map(mergeTodo);
答案 1 :(得分:-2)
我猜合并只用于数组。搜索对象"扩展"。也许将todo细节存储在单独的对象中是更好的解决方案。
使用下划线:
var result = [];
var entry = {};
_.each(todos, function(todo) {
_.each(todosMoreDetails, function(detail) {
if (todo.id == detail.id) {
entry = _.extend(todo, detail);
result.push(entry);
}
}
});
return result;