2

I have an array like this:

const data = [{
  color:"red",
  to:1,
  from:2,
  opacity:12
}]

I want something like this:

const converted = [{from:2}, {to:1}, {opacity:12}]

What I am trying is:

const mappedData = data.map(({from,to,opacity}) => ({from:from},{to:to},{opacity:opacity}))

but this is not working.

1
  • You can only return a single value from a function, so you would need to return an array ({from,to,opacity}) => [{from:from},{to:to},{opacity:opacity}]). To create a flat array from the result use flatMap() instead of map. Commented Aug 25, 2022 at 8:10

1 Answer 1

1

So you can loop through the array and for each object we can get the keys of the objects in the array and use a map to transform them to our desired output, Then the output will return an array, but we can use flatMap which will flatten the arrays returned into a single array of objects!

Thanks pilchard for teaching about flatMap!

const data = [{
color:"red",
to:1,
from:2,
opacity:12

}]

const arr = data.flatMap(x => Object.keys(x).map(data => ({[data]: x[data]})))

console.log(arr);

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

2 Comments

just use flatMap. And don't just post code, take the time to explain what wasn't working about the OP's code.
@pilchard Thanks flat map is awesome, first I post then I edit it

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.