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 create dictionary from another dictionary

If I have a dict like below:

const d = {"S1": [2, 3, 4], "S2": [5, 6, 7, 8]}

I want to create another dictionary that can get the len or the 1st element as value with the same key, like:

const n = {"S1": 3, "S2": 4} # len of the value array

I try to use a map like below:

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

Object.entries(d).map(([k, v]) => console.log(k, v))

It prints the key-value pair but how do I use that to create a new dictionary?

>Solution :

you have taken a good start in the right direction.
Object.fromEntries can be used to convert the key value pair array back to an object with the Object.entries + map you have started with

const d = {"S1": [2, 3, 4], "S2": [5, 6, 7, 8]}

const res = Object.fromEntries(Object.entries(d).map(([k,v]) => [k,v.length]))

console.log(res)

as an alternative you could achieve the same thing with Object.entries + reduce

const d = {"S1": [2, 3, 4], "S2": [5, 6, 7, 8]}

const res = Object.entries(d).reduce((acc,[k,v]) => ({...acc,[k]:v.length}),{})

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