给定这个JSON对象,lodash如何reach从对象中删除值?
{
total: 350,
SN1: {
reach: 200,
engagementRate: 1.35
},
SN2: {
reach: 150,
engagementRate: 1.19
}
}
Run Code Online (Sandbox Code Playgroud)
我一直试图迭代地删除()它但我总是得到一个未定义的对象作为回报所以我很肯定我做错了.这也是我第一次使用lodash,这可能是实际问题.
有人可以帮忙吗?
_.transform()将对象传递给另一个对象,并在将值传递给新对象时,检查该值是否为对象以及是否具有"reach"属性,如果是,则使用_.omit()获取新对象而不reach:
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);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
如果你需要一个处理多个嵌套对象级别的递归解决方案,这里deepOmit使用相同的想法但没有_.omit,并且可以用来删除多个键(请参阅代码中的注释):
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 valuesRun Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)
似乎没有深度omit,但您可以迭代对象中的所有键,并reach递归地从嵌套对象中删除:
function omitDeep(obj) {
_.forIn(obj, function(value, key) {
if (_.isObject(value)) {
omitDeep(value);
} else if (key === 'reach') {
delete obj[key];
}
});
}
Run Code Online (Sandbox Code Playgroud)
function omitDeep(obj) {
_.forIn(obj, function(value, key) {
if (_.isObject(value)) {
omitDeep(value);
} else if (key === 'reach') {
delete obj[key];
}
});
}
Run Code Online (Sandbox Code Playgroud)
var obj = {
total: 350,
SN1: {
reach: 200,
engagementRate: 1.35
},
SN2: {
reach: 150,
engagementRate: 1.19
}
};
function omitDeep(obj) {
_.forIn(obj, function(value, key) {
if (_.isObject(value)) {
omitDeep(value);
} else if (key === 'reach') {
delete obj[key];
}
});
}
omitDeep(obj)
console.log(obj);Run Code Online (Sandbox Code Playgroud)