Sherly Kim
Sherly Kim

Reputation: 71

comparing two maps and adding key to one map in javascript

I have two maps named maps1 and list1, and how do I compare their object and if the object is same, the key for maps1 goes for list1's key in javascript.

I know that to add values in map, the code is written

map1[anykey] = value; 

If map1 contains {hi , hello}, {a, b}, {c, d} and list1 contains [hi, a], I want to finally make a map2 that resembles something like this: {hi, hello}, {a, b}. is this anyway possible?

Upvotes: 0

Views: 1995

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

Just create a new, blank map object, loop through the list array, and copy over any properties whose names are in it:

// Create the blank object
var newObject = Object.create(null); // Or just {} if you prefer

// Loop through the array
list.forEach(function(name) {
    // Does the original object have a property by this name?
    if (name in originalObject) {
        // Yes, copy its value over
        newObject[name] = originalObject[name];
    }
});

Upvotes: 2

Related Questions