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

Iterate an array of objects

I have an array of objects.

myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]

I want to create a new dictionary from it:
newDict = {a:[1,2,3,4],c:[1,2,3,4]}

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

I’m totally new to Javascript and Node.js
Any kind of help is highly appreciated.
Thanks in advance.

>Solution :

Alternatively you can also do it in a for loop, in case you are unfamiliar with the reduce method.

const myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]

const wantedProperties = ['a', 'b', 'd']

const mydict = {}
for (const item of myArray) {
  for (const [key, value] of Object.entries(item)) {
    if (wantedProperties.includes(key)) {
     mydict[key] = (mydict[key] || []).concat(value)
    }
  }
}

console.log(mydict)
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