Search code examples
javascriptecmascript-6lodash

Create parent and child relationship using lodash


Combine both parent and chid JSON arrays based on the index value and add another found attribute to it.

Data: Comparison field: parentJSON - index childJSON - parent_index

Output: - parent - and its children - parent - and its children

parentJSON:
[{ index:1, name: 'a'}, {index:2, name: 'b'}, {index:3, name: 'c'}, {index:4, name: 'd'}]

childJSON:
[
  { index:1, name: 'aa', parent_index:1}, 
  {index:2, name: 'ab', parent_index:1}, 
  {index:3, name: 'ba', parent_index: 2}, 
  {index:4, name: 'bb', parent_index: 2}, 
  {index:5, name: 'ca', parent_index: 3}, 
  {index:6, name: 'ad', parent_index: 1}
]

output:
[
  { index:1, name: 'a'},
  { index:1, name: 'aa', parent_index:1, found: true}, 
  { index:2, name: 'ab', parent_index:1, found: true},
  { index:6, name: 'ad', parent_index:1, found: true},
  { index:2, name: 'b'},
  { index:3, name: 'ba', parent_index:2, found: true}, 
  { index:4, name: 'bb', parent_index:2, found: true},
  { index:3, name: 'c'},
  { index:5, name: 'ca', parent_index:3, found: true},
  { index:4, name: 'd'},
]

Plunker Link


Solution

  • let parentJSON =
    [{ index:1, name: 'a'}, {index:2, name: 'b'}, {index:3, name: 'c'}, {index:4, name: 'd'}]
    
    let childJSON =
    [
      { index:1, name: 'aa', parent_index:1}, 
      {index:2, name: 'ab', parent_index:1}, 
      {index:3, name: 'ba', parent_index: 2}, 
      {index:4, name: 'bb', parent_index: 2}, 
      {index:5, name: 'ca', parent_index: 3}, 
      {index:6, name: 'ad', parent_index: 1}
    ]
    
    let answer = [];
    
    parentJSON.forEach(parent => {
      answer.push(parent);
      
      childJSON.forEach(child => {
      	if(child.parent_index === parent.index){
        	child.found = true;
          
          answer.push(child);
        }
      })
    });
    
    console.log(answer)

    Without knowing how you are expecting to have childJSON that is not exist in parentJSON, the above solution made an assumption that all elements of childJSON has a parent_index link to parentJSON.

    Do let me know if you updated your question unless this is exactly what you want