skip to Main Content

How do we merge data from an object to an existing Map?

To create a Map from an object we can use this:

const myMap = new Map(Object.entries(myObject));

Is there a way to do the same to an existing Map() without using for loop?

const myObject = {
  test: "blah",
  ok: 123
}

const myMap = new Map(Object.entries(myObject));

const mySecondObject = {
  test: "new value",
  foo: "bar"
}

for(let i in mySecondObject)
{
  myMap.set(i, mySecondObject[i]);
}

console.log({size: myMap.size, test: myMap.get("test"), myMap});

2

Answers


  1. Note: the console in stackoverflow prevents Maps from being printed properly. It will work if you paste the code elsewhere.

    If the objective is concise code, you can do this:

    const myObject = {
      test: "blah",
      ok: 123
    }
    
    const myMap = new Map(Object.entries(myObject));
    
    const mySecondObject = {
      test: "new value",
      foo: "bar"
    }
    
    Object.entries(mySecondObject).forEach(x => myMap.set(...x))
    
    console.log({size: myMap.size, test: myMap.get("test"), myMap});

    If you don’t mind creating a new merged map, you can do so like this:

    const myObject = {
      test: "blah",
      ok: 123
    }
    
    const myMap = new Map(Object.entries(myObject));
    
    const mySecondObject = {
      test: "new value",
      foo: "bar"
    }
    
    const mergedMap = new Map([...myMap, ...Object.entries(mySecondObject)])
    
    console.log({size: mergedMap.size, test: mergedMap.get("test"), mergedMap});
    Login or Signup to reply.
  2. You’re looking for the Map.prototype.merge method from the collection methods proposal, which is still in stage 1. With a polyfill, you could write

    myMap.merge(Object.entries(mySecondObject));
    

    But currently no such method exists. There are many ways to have a helper method do the enumeration of the object keys and/or iterate over them, which would allow you to avoid for syntax, but they’re not as straightforward:

    for (const p in obj) map.set(p, obj[p]);
    Object.keys(obj).forEach(p => map.set(p, obj[p]));
    Object.entries(obj).forEach(([k, v]) => map.set(k, v));
    Object.entries(obj).forEach(map.set.apply.bind(map.set, map))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search