javascriptdictionary

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:

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)

    EDIT
    even better to avoid the creation of intermediate objects caused by spread operator (...)

    const d = {"S1": [2, 3, 4], "S2": [5, 6, 7, 8]}
    
    const res = Object.entries(d).reduce((acc, [k, v]) => (acc[k] = v.length, acc), {})
    
    console.log(res)