Home > Software engineering >  How to merge array inside object in javascript
How to merge array inside object in javascript

Time:09-08

I have decoded json like this:

[
    {
        "ID": "120",
        "NAME": "KRETEK",
        "children": [
            {
                "IDS": "01107",
                "VALUE": "6761114",
                "NAME": "GUD"
            }
        ]
    },
    {
        "ID": "120",
        "NAME": "KRETEK",
        "children": [
            {
                "IDS": "01108",
                "VALUE": "57904",
                "NAME": "POER"
            }
        ]
    },

]

is it possible to transform it into this?

[
    {
        "ID": "120",
        "NAME": "KRETEK",
        "children": [
            {
                "IDS": "01107",
                "VALUE": "6761114",
                "NAME": "GUD"
            },
            {
                "IDS": "01108",
                "VALUE": "57904",
                "NAME": "POER"
            }
        ]
    },
   
]

the data above was intended for amchart (https://www.amcharts.com/demos/collapsible-force-directed-tree/), thanks.

CodePudding user response:

i think u can use array reduce and array find

const data = [
    {
        "ID": "120",
        "NAME": "KRETEK",
        "children": [
            {
                "IDS": "01107",
                "VALUE": "6761114",
                "NAME": "GUD"
            }
        ]
    },
    {
        "ID": "120",
        "NAME": "KRETEK",
        "children": [
            {
                "IDS": "01108",
                "VALUE": "57904",
                "NAME": "POER"
            }
        ]
    },

]

const mergeArray = (originalArr) => {
  return originalArr.reduce((previous, obj) => {
      const isSameID = previous.find(item => item.ID === obj.ID)
      if (isSameID) {
        isSameID.children.push(...obj.children)
      } else {
        previous.push(obj);
      }
      return previous;
  }, [])
}

console.log(mergeArray(data))

  • Related