Object mapping function: extends the Map function to objects
P粉060528326
P粉060528326 2023-10-08 19:58:09
0
2
627

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粉060528326
P粉060528326

reply all(1)
P粉138871485

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. :-)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!