Reputation: 20885
I want to transfer properties from objA
to objB
while changing their names and overriding only if they are truthy. Using lodash but an ES6 solution would be even better.
This is what I have so far:
// My initial objects
const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};
// Extracting and renaming
let {x: a, y: b, z: c} = obj1;
// Sanitizing
const temp = _.pickBy({x, y, z}, _.identity);
// Merging A and B
return {...objB, ...objA}; // {x: 1, y: 8, z: 9}
Is there a less contrived way of doing this?
Upvotes: 0
Views: 1327
Reputation: 191976
Both solution use a Map to rename array keys, and Object#assign to merge objects (the snippets don't support object rest/spread).
ES2017
Use Object#entries (ES2017) to get the keys and values of objA
, rename and add them only if the value is not falsy.
const a2x = new Map([['a', 'x'], ['b', 'y'], ['c', 'z']]);
const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};
const result = Object.assign({}, objB,
Object.entries(objA).reduce((r, [k, v]) => v ?
Object.assign(r, { [a2x.get(k)]: v }) : r, {}));
console.log(result);
lodash:
Use _.mapKeys()
to change the names of the keys, then _.pickBy()
with _.identity()
to remove falsy values.
const a2x = new Map([['a', 'x'], ['b', 'y'], ['c', 'z']]);
const objA = {a: 1, b: '', c: null};
const objB = {x: 7, y: 8, z: 9};
const result = Object.assign({}, objB,
_.pickBy(_.mapKeys(objA, (v, k) => a2x.get(k)), _.identity));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Upvotes: 1