Home > Mobile >  Flatten child array to parent property
Flatten child array to parent property

Time:06-17

I have grouped by data but need to convert it into flat structure

data = [
   {
      "Name":"Gorba Technology",
      "Product":"Dell",
      "City":[
         "Delhi",
         "Mumbai"
      ]
   },
   {
      "Name":"Suvidha Computer",
      "Product":"Lenovo",
      "City":[
         "Deoghar"
      ]
   },
   {
      "Name":"Sara Laptop",
      "Product":"Dell",
      "City":[
         "Noida",
         "Delhi"
      ]
   }
]

Desired output

[{"Name":"Gorba Technology","City":"Delhi"},
{"Name":"Gorba Technology","City":"Mumbai"},
{"Name":"Suvidha Computer","City":"Deoghar"},
{"Name":"Sara Laptop","City":"Noida"},
{"Name":"Sara Laptop","City":"Delhi"}]

I try to do this approach but not worked

var result = data.map(({Name, City}) => City.map(item => {Name, item}));

I try to use flatMap but in my code, I was getting errors by lint. so without using flatMap need to achieve the output

CodePudding user response:

You need reduce instead of map

data.reduce((acc, {Name, City}) => {
  City.each((city) => {
    acc.push({Name, City: city});
  });
  return acc;
}, []);

CodePudding user response:

map() will always return the same number of items as your input array. That is not your requirement though.

One way to do this can be using reduce() and forEach().

You use destructure but for every list item you add multiple items into the array with the same Name:

const data = [
   {
      "Name":"Gorba Technology",
      "Product":"Dell",
      "City":[
         "Delhi",
         "Mumbai"
      ]
   },
   {
      "Name":"Suvidha Computer",
      "Product":"Lenovo",
      "City":[
         "Deoghar"
      ]
   },
   {
      "Name":"Sara Laptop",
      "Product":"Dell",
      "City":[
         "Noida",
         "Delhi"
      ]
   }
]

var result = data.reduce((acc,{Name,City}) => { 
  const items = [];
  City.forEach(city=> {
  items.push({Name , City : city});
  });
  return [...acc,...items];
},[]);

console.log(result);

CodePudding user response:

const data = [
   {
      "Name":"Gorba Technology",
      "Product":"Dell",
      "City":[
         "Delhi",
         "Mumbai"
      ]
   },
   {
      "Name":"Suvidha Computer",
      "Product":"Lenovo",
      "City":[
         "Deoghar"
      ]
   },
   {
      "Name":"Sara Laptop",
      "Product":"Dell",
      "City":[
         "Noida",
         "Delhi"
      ]
   }
];

const transformedData = [];

data.forEach(el => {
  if (el?.City?.length) {
    el.City.forEach(ct => {
      const obj = {...el, City: ct};
      transformedData.push(obj);
    })
  }
});

console.log(transformedData);

  • Related