Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript – Creating Object with specific format out of 2 Arrays

I have 2 Arrays.
The Array "people" just holds basic information of some people.
The Array "subscriptions" has a lot of different subscriptions to games.
I want to have have an Array, where I can sort of have an Overview of what game subscriptions each person has. This is not real code I use, I am just trying to get used to JavaScript.

an example Element of an Array called people:

{"number":4251,"name":"Alex","surname":"Scott"}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

an example Element of an Array called subscriptions:

{"number":4329,game:"Tetris"}

I want to make a new new Array with the following format:

person: (people[i]), subscriptions: [(subscriptions[j], subscriptions[j+k], …)]

What I tried:

const array3 = people.map(x => {"person": x , "subscriptions": subscriptions.filter(y => y.number === x.number)});

It get this Error:

SyntaxError: Unexpected token :

How can I insert multiple key value pairs in in these Objects?

>Solution :

This happens because your argument in the map is interperting the { as opening bracket of the method body.

const arr = [{some: 1, object: 2}, {some:3, object:4}]
arr.map((o) => {original: o, cool: 'yes'})

To resolve this you have to explicitly return the object or add additional parenthesis to let the interperter know that this is not the method body:

const arr = [{some: 1, object: 2}, {some:3, object:4}]
const mapped = arr.map((o) => {return {original: o, cool: 'yes'}})
console.log(mapped)
const arr = [{some: 1, object: 2}, {some:3, object:4}]
const mapped = arr.map((o) => ({original: o, cool: 'yes'}))
console.log(mapped)

I hope this helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading