0

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" }
    ]
  }
];
1

1 Answer 1

1

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)

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

2 Comments

Thank you @Kelvin Owen for the answer. It is working but I am getting wrong array 0: {name: "BMW", group: "X5", children: Array(3)} 1: {name: "car", group: "Ford", children: Array(2)} 2: {name: "Ford", group: "Focus", children: Array(2)}
The group name is wrong. I am working on that still. Do you have any Idea??

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.