Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new object from array of nested arrays that contains objects

I have the following array with nested arrays:

const options = [
  [
    {
      label: "Blue",
      option_id: "1"
    },
    {

      label: "Small",
      option_id: "2"
    }
  ],
  [
    {
      label: "Red",
      option_id: "1"
    },
    {
      label: "Large",
      option_id: "2"
    }
  ]
];

I want to create an array of objects from each pair, ex:

[
 {
   label: ”Blue Small“,
   option_id: [1,2]
 },
...
]

edit: thanks everyone for the great answers

like image 573
Stathis Ntonas Avatar asked Dec 10 '22 03:12

Stathis Ntonas


2 Answers

Use .map over the options array, and reduce each subarray into an object:

const options = [
  [
    {
      label: "Blue",
      option_id: "1"
    },
    {

      label: "Small",
      option_id: "2"
    }
  ],
  [
    {
      label: "Red",
      option_id: "1"
    },
    {
      label: "Large",
      option_id: "2"
    }
  ]
];
const result = options.map(arr =>
  arr.reduce(
    (a, { label, option_id }) => {
      a.label += (a.label ? ' ' : '') + label;
      a.option_id.push(option_id);
      return a;
    },
    { label: '', option_id: [] }
  )
);
console.log(result);
like image 94
CertainPerformance Avatar answered Dec 12 '22 16:12

CertainPerformance


reduce is a great way to these array transformations.

const options = [
  [
    {
      label: "Blue",
      option_id: "1"
    },
    {

      label: "Small",
      option_id: "2"
    }
  ],
  [
    {
      label: "Red",
      option_id: "1"
    },
    {
      label: "Large",
      option_id: "2"
    }
  ]
];

const newArray = options.reduce((prev,current)=>{
  const label = current.map(o=>o.label).join(' ')
  const optionid = current.map(o=>o.option_id)
  return [...prev,{option_id:optionid,label}]
},[])

console.log(newArray)
like image 37
Prithwee Das Avatar answered Dec 12 '22 17:12

Prithwee Das