Ano*_*ous 4 javascript ramda.js
我有这两个对象数组
todos: [
{
id: 1,
name: 'customerReport',
label: 'Report send to customer'
},
{
id: 2,
name: 'handover',
label: 'Handover (in CRM)'
},
]
Run Code Online (Sandbox Code Playgroud)
和:
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: []
}
]
Run Code Online (Sandbox Code Playgroud)
这样最终的对象数组将是两者的组合,基于对象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)'
}
]
Run Code Online (Sandbox Code Playgroud)
我尝试过merge mergeAll,mergeWithKey但我可能错过了一些东西
您可以使用中间组来实现此目的:
使用groupBy将todosMoreDetails数组转换为由todo属性ID键入的对象:
var moreDetailsById = R.groupBy(R.prop('id'), todosMoreDetails);
Run Code Online (Sandbox Code Playgroud)
moreDetailsById是一个对象,其中键是id,值是todos数组.如果id是唯一的,那么这将是一个单例数组:
{
1: [{
id: 1,
checked: false,
link: {
type: 'url',
content: 'http://something.com'
},
notes: []
}]
}
Run Code Online (Sandbox Code Playgroud)
现在通过将每个待办事项合并到您从分组视图中检索的详细信息来转换todos数组:
var finalTodos = R.map(todo => R.merge(todo, moreDetailsById[todo.id][0]), todos);
Run Code Online (Sandbox Code Playgroud)
另一种更详细的方式:
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);
Run Code Online (Sandbox Code Playgroud)