Muthukani K
Muthukani K

Reputation: 313

How to convert the JSON into nested Array format in typescript?

I am trying to convert the JSON to nested array format. The following one is my JSON data:

{
  "items": {
    "BMW": {
      "group": "car",
      "title": "BMW car"
    },
    "320": {
      "group": "BMW",
      "title": "320 Mod"
    },
    "X3": {
      "group": "BMW",
      "title": "X3"
    },
    "X5": {
      "group": "BMW",
      "title": "X5 Mod"
    },
    "Ford": {
      "group": "car",
      "title": "Ford car"
    },
    "Fiesta": {
      "group": "Ford",
      "title": "Fiesta Mod"
    },
    "Focus": {
      "group": "Ford",
      "title": "Focus Mod"
    }
  }
}

The JSON data has group. Based on that group I need to convert dynamically into desired array format. Below array is my expected output. Can anyone please help me to write program in typescript.

arrayObj = [
  {
    Name: "BMW car",
    id:"BMW",
    group: "car",
    children: [
      { Name: "320 Mod", id:"320", group: "BMW" },
      { Name: "X3 Mod", id:"X3", group: "BMW" },
      { Name: "X5 Mod", id:"X5", group: "BMW" }
    ]
  },
  {
    Name: "Ford car",
    group: "car",
    id: "Ford",
    children: [
      { Name: "Fiesta Mod", id:"Fiesta", group: "Ford" },
      { Name: "Focus Mod", id:"Focus", group: "Ford" }
    ]
  }
];

Upvotes: 0

Views: 519

Answers (1)

Owen Kelvin
Owen Kelvin

Reputation: 15083

You can use reduce() function to achieve this, see code below

const initialObject = {
  "items": {
    "BMW": {
      "group": "car",
      "title": "BMW"
    },
    "320": {
      "group": "BMW",
      "title": "320"
    },
    "X3": {
      "group": "BMW",
      "title": "X3"
    },
    "X5": {
      "group": "BMW",
      "title": "X5"
    },
    "Ford": {
      "group": "car",
      "title": "Ford"
    },
    "Fiesta": {
      "group": "Ford",
      "title": "Fiesta"
    },
    "Focus": {
      "group": "Ford",
      "title": "Focus"
    }
  }
}
const finalData = Object.values(Object.values(initialObject.items).reduce((prev, {group, title}) => {
  let children = prev[group]?.children
  if (!children) {
    children = []
  }
  children.push({name: title, group })
  return {...prev, [group]: {
    name: group,
    group:title,
    children
  }}
}, {}))


console.log(finalData)

Upvotes: 1

Related Questions