2017-03-09 23 views
1

我有这两个数组对象Ramda.js结合共享相同的属性ID

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)' 
      } 
     ] 

我试图与mergemergeAllmergeWithKey但我可能缺少的东西

回答

4

可以与中间GROUPBY实现这一点:

变换todosMoreDetails阵列分为使用GROUPBY通过待办事项属性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: [] 
     }] 
} 

现在通过合并每个待办事项改造待办事项数组分配给它的详细信息,你从分组视图检索:

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); 
+0

它的工作原理!但我不知道为什么。你可以简要解释一下吗?这将是伟大的 – Anonymous

+0

增加了一些我的建议的细节 –

0

我想合并只用于数组。搜索对象“扩展”。也许将待办事项的详细信息不存储在单独的对象中是更好的解决方案。

使用下划线:

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;