简体   繁体   English

设置对象属性(如果Javascript中为真)

[英]Set object properties if truthy in Javascript

I want to transfer properties from objA to objB while changing their names and overriding only if they are truthy . 我想将属性从objA转移到objB同时更改它们的名称并仅在它们为true时才覆盖它们。 Using lodash but an ES6 solution would be even better. 使用lodash但使用ES6解决方案会更好。

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? 有没有一种比较人为的方法?

Both solution use a Map to rename array keys, and Object#assign to merge objects (the snippets don't support object rest/spread). 两种解决方案都使用Map重命名数组键,并使用Object#assign合并对象(这些代码段不支持对象静止/扩展)。

ES2017 ES2017

Use Object#entries (ES2017) to get the keys and values of objA , rename and add them only if the value is not falsy. 使用对象#项 (ES2017)获得的键和值objA ,重命名和添加它们只有当值不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: lodash:

Use _.mapKeys() to change the names of the keys, then _.pickBy() with _.identity() to remove falsy values. 使用_.mapKeys()更改键的名称,然后使用_.pickBy()_.identity()删除伪造的值。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM