Search code examples
javascriptarraysjsonarray-merge

Merge object where key is matching


I'm new to typescript or node.js, I'm trying to combine the below JSON array Note: Not sure if the client allows any new dependencies or plugins can this be achieved without using underscore or jquery extend

[ { parentauthscopekey: 1, childauthscopekey: 2 },
  { parentauthscopekey: 12, childauthscopekey: 10 },
  { parentauthscopekey: 12, childauthscopekey: 11 },
  { parentauthscopekey: 13, childauthscopekey: 1 } ]

To

[ { parentauthscopekey: 1, childauthscopekey: [ 2, 1 ] },
  { parentauthscopekey: 12, childauthscopekey: [ 10, 11, 12 ] },
  { parentauthscopekey: 13, childauthscopekey: [ 1, 13 ] } ]

Tried the below code, It's just too many lines but does the job, but expecting something simple without using the hardcoded scope and scopeMap values

 table = [ { parentauthscopekey: 1, childauthscopekey: 2 },
  { parentauthscopekey: 12, childauthscopekey: 10 },
  { parentauthscopekey: 12, childauthscopekey: 11 },
  { parentauthscopekey: 13, childauthscopekey: 1 } ]
   
    scope=[1,12,13]
    scopeMap = new Set()

    table2 = []
    scope.forEach(parentauthscopekey => {
        table.forEach(row =>{
            if(row.parentauthscopekey == parentauthscopekey && !scopeMap.has(parentauthscopekey))
            {
                scopeMap.add(parentauthscopekey)
                childauthscopekey = []
                table.filter(c => c.parentauthscopekey == row.parentauthscopekey).forEach(r=>{
                    childauthscopekey.push(r.childauthscopekey)
                })
                childauthscopekey.push(parentauthscopekey)
                table2.push({parentauthscopekey, childauthscopekey})
            }
        })
    })
    console.log(table2)

Solution

  • you can :

    • use array.reduce to construct the expecting structure
    • recover or each entry the child matching parentauthscopekey with array.filter
    • and adding the current parentauthscopekey to childauthscopekey

    var data = [ { parentauthscopekey: 1, childauthscopekey: 2 },
      { parentauthscopekey: 12, childauthscopekey: 10 },
      { parentauthscopekey: 12, childauthscopekey: 11 },
      { parentauthscopekey: 13, childauthscopekey: 1 } ];
      
    var result = data.reduce((acc, current) => {
        if (!acc.some(one => one.parentauthscopekey === current.parentauthscopekey)) {
          var childs = data.filter(one => one.parentauthscopekey === current.parentauthscopekey).map(one => one.childauthscopekey);
          childs.push(current.parentauthscopekey);
          acc.push({
            parentauthscopekey: current.parentauthscopekey,
            childauthscopekey: childs
          })
        }
      return acc;
    }, []);
    
    console.log(result);