search

Home  >  Q&A  >  body text

Object mapping function: extends the Map function to objects

I have an object:

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

I'm looking for a native method similar to Array.prototype.map which can be used like this:

newObject = myObject.map(function (value, label) {
    return value * value;
});

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

Does JavaScript have a map function for such an object? (I want this for Node.JS, so I don't care about cross-browser issues.)

P粉060528326P粉060528326530 days ago929

reply all(2)I'll reply

  • P粉138871485

    P粉1388714852023-10-09 15:14:40

    Using JS ES10 / ES2019 How about writing one sentence per line?

    Using Object.entries( ) and <代码>Object.fromEntries():

    let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
    

    Write the same thing as a function:

    function objMap(obj, func) {
      return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
    }
    
    // To square each value you can call it like this:
    let mappedObj = objMap(obj, (x) => x * x);
    

    This function also uses recursion to square nested objects:

    function objMap(obj, func) {
      return Object.fromEntries(
        Object.entries(obj).map(([k, v]) => 
          [k, v === Object(v) ? objMap(v, func) : func(v)]
        )
      );
    }
    
    // To square each value you can call it like this:
    let mappedObj = objMap(obj, (x) => x * x);
    

    In ES7/ES2016 you cannot use Objects.fromEntries, but you can use Object.assign with Expand operators and Compute key namesSyntax:

    let newObj = Object.assign({}, ...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
    

    ES6 / ES2015 Object.entries is not allowed, but you can use Object.keys instead:

    let newObj = Object.assign({}, ...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
    

    ES6 also introduced the for...of loop, allowing a more imperative style:

    let newObj = {}
    
    for (let [k, v] of Object.entries(obj)) {
      newObj[k] = v * v;
    }
    


    Array.reduce()

    You can also use Object.fromEntries and Object.assign /Web /JavaScript/Reference/Global_Objects/Array/reduce" rel="noreferrer">reduce To do this:

    let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
    


    Inherited properties and prototype chain:

    In some rare cases, you may need to map a class object that is in its prototype chain . In this case, Object.keys() and Object.entries() will not work because these functions do not contain a prototype chain.

    If you need to map inherited properties, you can use for (key in myObj) {...}.

    The following are examples of such situations:

    const obj1 = { 'a': 1, 'b': 2, 'c': 3}
    const obj2 = Object.create(obj1);  // One of multiple ways to inherit an object in JS.
    
    // Here you see how the properties of obj1 sit on the 'prototype' of obj2
    console.log(obj2)  // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
    
    console.log(Object.keys(obj2));  // Prints: an empty Array.
    console.log(Object.entries(obj2));  // Prints: an empty Array.
    
    for (let key in obj2) {
      console.log(key);              // Prints: 'a', 'b', 'c'
    }
    

    But please do me a favor and avoid inheritance. :-)

    reply
    0
  • P粉826429907

    P粉8264299072023-10-09 10:42:04

    There is no native map to the Object object, but how about this:

    var myObject = { 'a': 1, 'b': 2, 'c': 3 };
    
    Object.keys(myObject).forEach(function(key, index) {
      myObject[key] *= 2;
    });
    
    console.log(myObject);
    // => { 'a': 2, 'b': 4, 'c': 6 }

    reply
    0
  • Cancelreply