Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (13.1k points)

Can anyone help me with a map function in JavaScript? I want the below code with some native method:

newObject = myObject.map(function (value, label) {

    return value * value;

});

// newObject is now { 'a': 1, 'b': 4, 'c': 9 }

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use the below code for implement it:

var myObject = { 'a': 1, 'b': 2, 'c': 3 };

// returns a new object with the values at each key mapped using mapFn(value)

function objectMap(object, mapFn) {

  return Object.keys(object).reduce(function(result, key) {

    result[key] = mapFn(object[key])

    return result

  }, {})

}

var newObject = objectMap(myObject, function(value) {

  return value * 2

})

console.log(newObject);

// => { 'a': 2, 'b': 4, 'c': 6 }

console.log(myObject);

// => { 'a': 1, 'b': 2, 'c': 3 }

It will return a new object and leaves the original as it is.

I hope this will help.

Want to become a Java Expert? Join Java Certification now!!

Want to know more about Java? Watch this video on Java Course | Java Tutorial for Beginners:

Related questions

0 votes
1 answer
0 votes
3 answers
asked Sep 20, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 9, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
asked Jun 20, 2019 in Java by Ritik (3.5k points)

Browse Categories

...