0

I want to match id and parentId and get the new object

element can take more than one data and must be nested according to id matching

I couldn't find how to match and can I search the new list after converting?

is it possible to do such a dynamic function?

I will use this code in an angular project

First Array

[
  {
    id: '1',
    parentId: 0,
    name: 'x'
  },
  {
    id: '2',
    parentId: 1,
    name: 'y'
  },
  {
    id: '3',
    parentId: 2,
    name: 'z'
  },
  {
    id: '4',
    parentId: 2,
    name: 'q'
  },
  {
    id: '5',
    parentId: 3,
    name: 'e'
  },
  {
    id: '6',
    parentId: 5,
    name: 'r'
  }
]

new object

{
  element: [
    {
      data: {
        id: '1',
        parentId: 0,
        name: 'x'
      },
      element: [
        {
          data: {
            id: '2',
            parentId: 1,
            name: 'y'
          },
          element: [
            {
              data: {
                id: '3',
                parentId: 2,
                name: 'z'
              },
              element: [
                {
                  data: {
                    id: '5',
                    parentId: 3,
                    name: 'e'
                  },
                  element: [
                    {
                      data: {
                        id: '6',
                        parentId: 5,
                        name: 'r'
                      },
                      element: [

                      ]
                    }
                  ]
                }
              ]
            },
            {
              data: {
                id: '4',
                parentId: 2,
                name: 'q'
              },
              element: [

              ]
            }
          ]
        }
      ]
    }
  ]
}
2
  • 1
    I think this is what you want. stackoverflow.com/questions/19222113/… Commented May 9, 2020 at 21:28
  • you can use lodash to achieve this. Sorry for bad formatting. The question was closed. Couldn't post as an answer function transformToTree(arr){ var nodes = {}; return arr.filter(function(obj){ var id = obj["id"], parentId = obj["parentId"]; nodes[id] = _.defaults(obj, nodes[id], { element: [] }); parentId && (nodes[parentId] = (nodes[parentId] || { element: [] }))["element"].push(obj); return !parentId; }); } Commented May 9, 2020 at 22:11

1 Answer 1

1

In the MSN Javascript documentation look up Array.find(). Basically, pass a simple expression for the search.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.