-1

I'm building myself an admin dashboard in NextJS 13, and I have been struggling with converting arrays using ES6 functions.

For instance, I have the following array:

["","1","Mobile Phones"], //corresponding to ParentID, ID, Name
["1","2","Apple"],
["1","3","Samsung"],
["","4","Tablets"],
["4","5","Huawei"],

How can I convert it to the below object array like the below?

[
  {
    id: 1,
    name: "Mobile Phones",
    children: [
      {
        id: 2,
        name: "Apple",
        children: [],
      },
      {
        id: 3,
        name: "Samsung",
        children: [],
      },
    ],
  },
  {
    id: 4,
    name: "Tablets",
    children: [
      {
        id: 5,
        name: "Huawei",
        children: [],
      },
    ],
  },
];

I have tried using array.map but I got the wrong result as shown below

[
  {
    id: 1,
    name: "Mobile Phones",
    children: [],
  },
  {
    id: 2,
    name: "Apple",
    children: [],
  },

  {
    id: 3,
    name: "Samsung",
    children: [],
  },
  {
    id: 4,
    name: "Tablets",
    children: [],
  },
  {
    id: 5,
    name: "Huawei",
    children: [],
  },
];
4

1 Answer 1

1

Create a map of non empty parentID to object. Then push the top level objects in the result array.

function buildObjectFromArray(arr) 
{
  const map = new Map();

  // Create a map of parent IDs to their respective objects
  for (const [parentId, id, name] of arr) {
    map.set(id, { id: parseInt(id), name, children: [] });
    if (parentId !== "") {
      const parent = map.get(parentId);
      parent.children.push(map.get(id));
    }
  }

  // Find the top-level objects (ParentID === "")
  const result = [];
  for (const [parentId, id, name] of arr) {
    if (parentId === "") {
      result.push(map.get(id));
    }
  }

  return result;
}



const objArr = buildObjectFromArray(
  [
    ["", "1", "Mobile Phones"],
    ["1", "2", "Apple"],
    ["1", "3", "Samsung"],
    ["", "4", "Tablets"],
    ["4", "5", "Huawei"],
    ["", "6", "X"],
    ["6", "7", "Y"],
    ["7", "8", "Z"],
]);

console.log(objArr);

Note: This solution assumes that the parent is declared before its children in the input.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.