Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 copy properties to target only if they already exist

Essentially what I want

let schema = {
       name: null,
       lastname: null
    }

let values = {
       name: "John",
       unwanted: "haxor"
    }

to end up in:

console.log(sanitized); // {name: "John", lastname: null}

--

Using Object.assign(schema, values) ends up with the unwanted value.

Is there a simple way?

Edit: I should add, this is to avoid using a library like lodash or underscore, so if the solution is overly complex, they would be preferable solutions.

like image 974
Dan Avatar asked Jul 07 '16 16:07

Dan


Video Answer


2 Answers

There is no builtin method which achieves that. However, there is a simple (almost trivial) way to do it:

const sanitized = {};
for (const p in schema)
    sanitized[p] = (p in object ? object : schema)[p];
like image 149
Bergi Avatar answered Sep 28 '22 05:09

Bergi


Just retrieve the same key from the other object:

Object.keys(schema).forEach(key => schema[key] = (key in values ? values : schema)[key]);

If you want to create a new object:

var newObj = {};
Object.keys(schema).forEach(key => newObj[key] = (key in values ? values : schema)[key]);

Also, this is compatible with previous version of ES as well (if you do not use arrow function, of course).

The (key in values ? values : schema)[key]) part assures properties that are only in first schema aren't set to undefined

like image 41
rpadovani Avatar answered Sep 28 '22 05:09

rpadovani