给定这个
JSON对象,lodash如何从对象中删除到达值?
{ total: 350,SN1: { reach: 200,engagementRate: 1.35 },SN2: { reach: 150,engagementRate: 1.19 } }@H_404_3@我一直试图迭代地删除()它但我总是得到一个未定义的对象作为回报所以我很肯定我做错了.
这也是我第一次使用lodash,这可能是实际问题.有人可以帮忙吗?
解决方法
_.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);@H_404_3@<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>@H_404_3@如果你需要一个处理多个嵌套对象级别的递归解决方案,这里是deepOmit,它使用相同的想法,但没有_.omit,可以用来删除多个键(参见代码中的注释):
var obj = { total: 350,engagementRate: 1.35,DEEP_SN1: { reach: 200,engagementRate: 1.35 } },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,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@H_404_3@<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>@H_404_3@