javascriptarraysecmascript-6array-maparray-reduce

Javascript array restructuring for nested array


I have an array of objects as mentioned below.

const inputArray =[
  {
    name: "Energy",
    quantity: [
      {
        qval: "100 ",
        unit: "unit1"
      },
      {
        qval: "200 ",
        unit: "unit2"
      }
    ],
  },
  {
    name: "Fat",
    quantity: [
      {
        qval: "300",
        unit: "unit3"
      }
    ],
  },
]

I'm trying to restructure this array using the following code and I got something as mentioned below

const outputArray = inputArray.map(function(item,i) {
  return {
    name: item.name,
    amount: (item.quantity[0] && 
    item.quantity[0].qval+item.quantity[0].unit)+'|'+ (item.quantity[1] && item.quantity[1].qval+item.quantity[1].unit),
 };

});

And here is the output I got

[
  {name: "Energy", amount: "100 unit1|200 unit2"}
  {name: "Fat", amount: "300unit3|undefined"}
]

Since I'm new to this, I don't think this is a good method, please suggest any simpler neat code. I'm expecting

[
  {name: "Energy", amount: "100 unit1|200 unit2"}
  {name: "Fat", amount: "300unit3"}
]

Also I need to remove 'undefined' if that value doesn't exist. Please suggest.


Solution

  • there you go

    inputArray.map(item => ({
        name: item.name,
        amount: item.quantity.reduce((accumulator, currentValue) => (accumulator+currentValue.qval+currentValue.unit+"|"),"").slice(0, -1)
    }))