skip to Main Content

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?

2

Answers


  1. 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)
    Login or Signup to reply.
  2. See inline comments:

    function mapLengths(obj) {
      // Convert entries back to object:
      return Object.fromEntries(
        // Convert "d" to entries (tuples) and map:
        Object.entries(obj).map(
          // Return a tuple with the key and value of the "length" property:
          ([k, v]) => [k, v?.length],
        ),
      );
    }
    
    const d = { "S1": [2, 3, 4], "S2": [5, 6, 7, 8] };
    const n = mapLengths(d);
    console.log(n); // { S1: 3, S2: 4 }
    
    // If there is a value without a "length" property,
    // the optional chaining operator will prevent an invalid access exception
    // and just return "undefined":
    
    const d2 = {
      "S0": null,
      "S1": [2, 3, 4],
      "S2": [5, 6, 7, 8],
      "S3": {},
      "S4": "hello world",
    };
    
    const n2 = mapLengths(d2);
    console.log(n2); // { S0: undefined, S1: 3, S2: 4, S3: undefined, S4: 11 }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search