Lodash递归删除项目 [英] Lodash remove items recursively

查看:167
本文介绍了Lodash递归删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此JSON对象,lodash如何从对象中删除到达值?

Given this JSON object, how does lodash remove the reach value from the objects?

{ 
    total: 350,
    SN1: { 
        reach: 200,
        engagementRate: 1.35
    },
    SN2: {
        reach: 150,
        engagementRate: 1.19
    }
}

我一直试图迭代地删除它()但我总是得到一个未定义的对象作为回报,所以我很肯定我做错了。
这也是我第一次使用lodash,这可能是实际问题。

I've been trying to iteratively remove() it but I always get an undefined object in return so I'm positive I'm doing it wrong. This is also the first time I'm using lodash, so that might be the actual problem.

任何人都可以帮忙吗?

推荐答案

_。transform () 将对象传递给另一个对象,并在将值传递给新对象时,检查该值是否为对象以及是否具有reach属性,如果是,则使用 _。omit() 获取新对象没有到达

var obj = {
  total: 350,
  SN1: {
    reach: 200,
    engagementRate: 1.35
  },
  SN2: {
    reach: 150,
    engagementRate: 1.19
  }
};

var result = _.transform(obj, function(result, value, key) {
  result[key] = _.isObject(value) && `reach` in value ? _.omit(value, 'reach') : value;
});

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

如果你需要一个可以处理多个的递归解决方案嵌套对象级别,这里是 deepOmit ,它使用相同的想法,但没有 _。省略,可以使用删除多个键(请参阅代码中的注释):

And if you need a recursive solution that will handle multiple nested object levels, here is deepOmit, which uses the same idea, but without _.omit, and can be used to remove multiple keys (see comments in code):

var obj = {
  total: 350,
  SN1: {
    reach: 200,
    engagementRate: 1.35,
    DEEP_SN1: {
      reach: 200,
      engagementRate: 1.35
    }
  },
  SN2: {
    reach: 150,
    engagementRate: 1.19
  }
};

function deepOmit(obj, keysToOmit) {
  var keysToOmitIndex =  _.keyBy(Array.isArray(keysToOmit) ? keysToOmit : [keysToOmit] ); // create an index object of the keys that should be omitted

  function omitFromObject(obj) { // the inner function which will be called recursivley
    return _.transform(obj, function(result, value, key) { // transform to a new object
      if (key in keysToOmitIndex) { // if the key is in the index skip it
        return;
      }

      result[key] = _.isObject(value) ? omitFromObject(value) : value; // if the key is an object run it through the inner function - omitFromObject
    })
  }
  
  return omitFromObject(obj); // return the inner function result
}

console.log(deepOmit(obj, 'reach')); // you can use a string for a single value

console.log(deepOmit(obj, ['reach', 'engagementRate'])); // you can use an array of strings for multiple values

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

这篇关于Lodash递归删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆