如何在对象上保留某些属性?

时间:2019-02-10 02:36:37

标签: javascript arrays object ecmascript-6 lodash

我有这个对象。如果某个属性的值为 null ,我将删除该属性。但是我有一些特殊的属性,无论什么情况,我都想保留 (即使它们的值为null)。到目前为止,我的代码运行良好,但是我不喜欢必须反复使用OR || 运算符的事实。 示例:

  

key ==='alwaysCountWithMe'||键==='ABC'||键==='doNotDeleteMe'   ||键==='specialProperty'

这是我的代码:

var object = {
  "firstname": null,
  "lastname": "White",
  "ABC": null,
  "hobby": null,
  "c": 3,
  "alwaysCountWithMe": null,
  "doNotDeleteMe": null,
  "specialProperty": null,
};

console.log(_.pickBy(object, (value, key) => !!value || key === 'alwaysCountWithMe' || key === 'ABC' || key === 'doNotDeleteMe' || key === 'specialProperty'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

是否有一种更清洁的方法,而不必一遍又一遍地使用 || ?。

4 个答案:

答案 0 :(得分:2)

是的,使用数组和includes

var object = {
  "firstname": null,
  "lastname": "White",
  "ABC": null,
  "hobby": null,
  "c": 3,
  "alwaysCountWithMe": null,
  "doNotDeleteMe": null,
  "specialProperty": null,
};

console.log(_.pickBy(object, (value, key) => !!value || ['alwaysCountWithMe', 'ABC', 'doNotDeleteMe', 'specialProperty'].includes(key)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 1 :(得分:2)

使用一组键始终保留,并检查其是否includes(key)

var object = {
  "firstname": null,
  "lastname": "White",
  "ABC": null,
  "hobby": null,
  "c": 3,
  "alwaysCountWithMe": null,
  "doNotDeleteMe": null,
  "specialProperty": null,
};
const alwaysKeep = ['alwaysCountWithMe', 'ABC', 'doNotDeleteMe', 'specialProperty'];

console.log(_.pickBy(object, (value, key) => !!value || alwaysKeep.includes(key)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 2 :(得分:2)

我将alwaysKeep保留为Object,然后我不需要每次都遍历它,因为JS对象使用哈希,因此我可以O(1)的时间复杂度进行访问

var object = {"firstname": null,"lastname": "White","ABC": null,"hobby": null,"c": 3,"alwaysCountWithMe": null,"doNotDeleteMe": null,"specialProperty": null,};

const alwaysKeep = {'alwaysCountWithMe': true, 'ABC': true, 'doNotDeleteMe': true, 'specialProperty':true};

console.log(_.pickBy(object, (value, key) => !!value || alwaysKeep[key]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 3 :(得分:1)

一种解决方案是将密钥保留在Set上。

var object = {
  "firstname": null,
  "lastname": "White",
  "ABC": null,
  "hobby": null,
  "c": 3,
  "alwaysCountWithMe": null,
  "doNotDeleteMe": null,
  "specialProperty": null,
};

const keysSet = new Set(['alwaysCountWithMe', 'ABC', 'doNotDeleteMe', 'specialProperty']);

console.log(_.pickBy(object, (value, key) => !!value || keysSet.has(key)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>