1

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

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

3 Comments

I meant to say that I have tried to modify the group by function to my expected result but didn't worked. Can you explain me how it works?
The destructured name takes the name property from the object being mapped over. The ...rest collects the rest of the properties (the numeric ones) into an object. Then return a new object with the name, and the multipolygon as the values of the rest object.
Elegant solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.