代码之家  ›  专栏  ›  技术社区  ›  Devmix

是否删除以空数组作为其值的属性?

  •  0
  • Devmix  · 技术社区  · 6 年前

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

    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 回复  |  直到 6 年前
        1
  •  0
  •   Ori Drori    6 年前

    你可以使用 _.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>
        2
  •  0
  •   Akrion    6 年前

    你可以使用 _.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>