删除具有空数组作为其值的属性?

时间:2018-12-18 21:18:57

标签: javascript lodash

我有这个对象,我正在尝试执行以下操作:

1)删除其值为空数组的属性。

2)如果属性的值是仅包含1个元素的数组,则将值设置为该元素而不是数组。

示例:

colors: ['blue'] 

然后将其设置为

colors: 'blue'

到目前为止,我有这段代码仅删除了值为空的属性

var obj = {name: 'John', lastname: 'Smith', colores: ['blue'], movies: [], age: 20, country: null};

var result = _.pickBy(obj);
console.log(result); // {name: "John", lastname: "Smith", colores: Array(1), movies: Array(0), age: 20}

如何使其正常工作,以便返回此信息:

{name: "John", lastname: "Smith", colores: 'blue', age: 20}

2 个答案:

答案 0 :(得分:0)

您可以使用_.transform()更改对象的值并删除键:

var obj = {name: 'John', lastname: 'Smith', colores: ['blue'], movies: [], age: 20, country: null};

var result = _.transform(obj, (acc, v, k) => {
  if(_.isNil(v) || _.isObject(v) && _.isEmpty(v)) return;
  
  if(_.isArray(v) && _.eq(v.length, 1)) acc[k] = _.head(v);
  else acc[k] = v;
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 1 :(得分:0)

您可以使用_.omitBy_.mapValues

let obj = { name: 'John', lastname: 'Smith', colores: ['blue'], movies: [], age: 20, country: null }; 

let result = _.omitBy(obj, x => _.isEmpty(x) && !_.isNumber(x))
result = _.mapValues(result, x => _.isArray(x) && !_.isEmpty(x) ? _.first(x) : x)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

具有链接:

let obj = { name: 'John', lastname: 'Smith', colores: ['blue'], movies: [], age: 20, country: null };

let result = _(obj)
  .omitBy(x => _.isEmpty(x) && !_.isNumber(x))
  .mapValues(x => _.isArray(x) && x.length == 1 ? _.first(x) : x)
  .value()

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>