简体   繁体   中英

Convert Json to parent,child relation structure

Want to convert JSON into parent child relation. Json consist category and sub category , match Category and push subCategory into it as child

JSON

    [  {
         "id": 0,
         "category": "Business Services",
          "subCategory": "Printing Services",
         "isChecked": false
        },
       {
      "id": 1,
      "category": "Business Services",
      "subCategory": "Waste Management Service",
      "isChecked": false
       },
      {
      "id": 2,
      "category": "Consumer Products Manufacture - Food and Beverage",
      "subCategory": "Alcoholic beverages",
      "isChecked": false
    },
      {
       "id": 3,
       "category": "Consumer Products Manufacture - Food and Beverage",
       "subCategory": "Cakes and Pastries",
       "isChecked": false
     },
     {
      "id": 4,
      "category": "Finance",
      "subCategory": "Finance Software and Services",
      "isChecked": false
   },
    {
    "id": 5,
    "category": "Finance",
    "subCategory": "Insurance",
    "isChecked": false
    },
  ]

Want to have below json form from what i have original json

       {category: 'Business Service',
          [ {value:'Printing Service'},{value:'Waste Management 
       service'},..]
      }, 
       { category :'Consumer products manufacture -Food and Beverage',
            [{..}...]
       }

You can try to reduce your input array and simply sort your output like so:

 const input = [{ "id": 0, "category": "Business Services", "subCategory": "Printing Services", "isChecked": false }, { "id": 1, "category": "Business Services", "subCategory": "Waste Management Service", "isChecked": false }, { "id": 2, "category": "Consumer Products Manufacture - Food and Beverage", "subCategory": "Alcoholic beverages", "isChecked": false }, { "id": 3, "category": "Consumer Products Manufacture - Food and Beverage", "subCategory": "Cakes and Pastries", "isChecked": false }, { "id": 4, "category": "Finance", "subCategory": "Finance Software and Services", "isChecked": false }, { "id": 5, "category": "Finance", "subCategory": "Insurance", "isChecked": false }, ] const output = input.reduce((acc, cur) => { if (typeof acc[cur.category] == "undefined") acc[cur.category] = [] acc[cur.category].push({ value: cur.subCategory }); return acc; }, {}) console.log(output) 

You could take a Map , collect all same categories and get a result with Array.from and a mapping of the wanted structure.

 var data = [{ id: 0, category: "Business Services", subCategory: "Printing Services", isChecked: false }, { id: 1, category: "Business Services", subCategory: "Waste Management Service", isChecked: false }, { id: 2, category: "Consumer Products Manufacture - Food and Beverage", subCategory: "Alcoholic beverages", isChecked: false }, { id: 3, category: "Consumer Products Manufacture - Food and Beverage", subCategory: "Cakes and Pastries", isChecked: false }, { id: 4, category: "Finance", subCategory: "Finance Software and Services", isChecked: false }, { id: 5, category: "Finance", subCategory: "Insurance", isChecked: false }], grouped = Array.from( data.reduce((m, { category, subCategory }) => m.set(category, [...(m.get(category) || []), subCategory]), new Map), ([category, values]) => ({ category, subCategories: values.map(value => ({ value })) }) ); console.log(grouped); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You can also do it like this:

Check if key does not exist then create the key and append value, otherwise extract previous values and append the new one

const result = arr.reduce((acc, curr, i) => {
  if (!Object.keys(acc).includes(curr.category)) {
    acc = {
      ...acc,
      [curr.category]: [{ 'value': curr.subCategory }]
    }
  }
  else {
    acc[curr.category] = [...acc[curr.category], { 'value': curr.subCategory }]

  }
  return acc;

}, [])

console.log('output result', result);

Proof example: https://stackblitz.com/edit/stackoverflow-answer-json-transormation2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM