[英]Lodash Not executing the nested method,
given this array var array = [{a:1, b: 2, c: 3}, {a: 2, b: 4, c: 4}]
. 给定此数组
var array = [{a:1, b: 2, c: 3}, {a: 2, b: 4, c: 4}]
。
I want to iterate through each item in the array and omit the key c
and it's value using lodash. 我想遍历数组中的每个项目,并省略键
c
及其使用lodash的值。
here is the method I tried 这是我尝试的方法
_.each(array, function (obj) { return _.omit(obj, ['a']); });
Expected Output should be // [{b: 2, c: 3}, {b: 4, c: 4} ]
but lodash returns the original array // [{a:1, b: 2, c: 3}, {a: 2, b: 4, c: 4}]
预期输出应为
// [{b: 2, c: 3}, {b: 4, c: 4} ]
但lodash返回原始数组// [{a:1, b: 2, c: 3}, {a: 2, b: 4, c: 4}]
Instead of forEach()
to return new modified array you should use map()
, also first parameter is array. 代替
forEach()
返回新的修改后的数组,您应该使用map()
,而且第一个参数是array。
var array = [{a:1, b: 2, c: 3}, {a: 2, b: 4, c: 4}] var result = _.map(array, function (obj) { return _.omit(obj, ['a']); }); console.log(JSON.stringify(result, 0, 4))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
A probably-not-the-lo-dash-iest way of handling it (assuming you actually want to omit a
): 处理它可能-不是最LO-划线IEST方式(假设你真的想省略
a
):
_.each(lnkn, function (obj) {
var returnObj = {};
for (prop in obj) {
if (obj.hasOwnProperty(prop) {
if (prop !== 'a') {
returnObj[prop] = obj[prop];
}
}
}
return returnObj;
});
_.forEach
is supposed to return the original array. _.forEach
应该返回原始数组。 You re looking for _.map
. 您正在寻找
_.map
。
const array = [{a:1, b: 2, c: 3}, {a: 2, b: 4, c: 4}]; const result = _.map(array, obj => _.omit(obj, 'a')); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Or you can modify the objects in place: 或者,您可以在适当位置修改对象:
const array = [{a:1, b: 2, c: 3}, {a: 2, b: 4, c: 4}]; _.forEach(array, obj => { delete obj.a; }); console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.