Pixele9
Pixele9

Reputation: 442

How to convert objects inside array to nested array JavaScript?

I have an array containing objects that every element but the last one are objects, but I want to convert them into an array of arrays and add the last element.

To be more explicit here is how I have it:

[
    { 0: [1,2], 1: [6,2], name: "" },
    { 0: [3,4], 1: [2,2], name: "" }
]

and the result I want is this one:

[
    { multipolygon: [ [1,2], [6,2] ], name: ""},
    { multipolygon: [ [3,4], [2,2] ], name: ""}
]

Each single array contained inside the original array is converted into an array of those arrays.

I have tried doing this:

const zonesArray = zones.map(el => Object.values(el)) // obj => array
const polygons = zonesArray.filter(el => el.pop()) // array without name

to get all the arrays contained inside the obj but then I realized how can I replace this into the original objects.

I have tried to modify the groupBy function found on MDN:

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

But I can't seem to find the answer

Upvotes: 1

Views: 60

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

It doesn't look like you're trying to group by a property, you're trying to transform each object in the array separately - which can be done by taking the name and the numeric properties together when mapping, then returning the shape of the new object:

const arr = [
    { 0: [1,2], 1: [6,2], name: "" },
    { 0: [3,4], 1: [2,2], name: "" }
];

const result = arr.map(({ name, ...rest }) => ({
  name,
  multipolygon: Object.values(rest)
}));
console.log(result);

Upvotes: 3

Related Questions