LuisPinto
LuisPinto

Reputation: 1697

How can I map an Object into another one?

So let's imagine I have an Object like

const foo = {
 name: 'Name',
 age: 23
}

So I want to map those values in the following structure.

const var = {
 _name?
 _age?
 _location?
}

_ only reflect that they can have a different name they are not only _+ foo key name

Is there a way I can do that instead of doing:

var._name = foo.name
var._age = foo.age

Is there another way I could do this? As I'll have some keys in the var structure which won't be present in the foo structure. So If I do as I proposed, then I'll end up with some undefined values in the new structure.

Upvotes: 1

Views: 554

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138537

 const result = Object.fromEntries(
   Object.entries(foo).map(([k, v]) => (["_" + k, v]))
 );

Objects can be iterated as key value pairs.

Or if you want to replace property by property, use Object.assign:

 const result = Object.assign({},
   foo.original && { renamed: foo.original },
   foo.original2 && { renamed2: foo.original2 }
 });

For sure that can be moved into a helper function:

 const rename = mapper => obj => Object.assign(...Object.entries(mapper).map(([o, n]) => obj[o] && { [n]: obj[o] }));

/* Or more pragmatic:
const rename = mapper => obj => {
  const result = {};
  for(const [o, n] of Object.entries(mapper)) if(o in obj) result[n] = obj[o];
  return result;
};
*/

 const result = rename({original: "renamed", original2: "renamed2" })(foo);

Upvotes: 4

Related Questions