Transform array into an object using an attribute as a reference

I need to convert an Array into an object, but I have no idea how to do this.

When I receive data from my API, it comes in the following structure:

[
  {
    id: 1,
    identifier: '0'
  },
  {
    id: 4,
    identifier: '0,1,0'
  },
  {
    id: 3,
    identifier: '0,1'
  },
  {
    id: 2,
    identifier: '0,0'
  }
]

After receiving the data I need to execute a method to convert them to the following structure based on the identifier attribute:

{
  id: 1,
  children: [
    {
      id: 2
    },
    {
      id: 3,
      children: [
        {
          id: 4
        }
      ]
    }
  ]
}

Any idea how I can get the desired result?

11 thoughts on “Transform array into an object using an attribute as a reference”

  1. You can use split method to get an array from identifier string and then use reduce and forEach to build nested structure.

    const data = [{"id":1,"identifier":"0"},{"id":2,"identifier":"0,0"},{"id":3,"identifier":"0,1"},{"id":4,"identifier":"0,1,0"}]
    
    const result = []
    
    data.forEach(o => {
      o.identifier.split(',').reduce((r, e, i, a) => {
          if (!r[e]) r[e] = { children: [] }
          if (!a[i + 1]) r[e].id = o.id
          return r[e].children;
        }, result)
    })
    
    console.log(result)
    Reply

Leave a Comment