gpt4 book ai didi

javascript - 如果值为 0,则从数组中的对象中删除属性

转载 作者:行者123 更新时间:2023-11-30 09:31:16 25 4
gpt4 key购买 nike

如果对象的值为零,我如何从对象中删除该属性?

var row = [{
2013: "0",
2014: "0",
2015: "95163",
carseries: "Sindelfingen"
},{
2013: "0",
2014: "38954",
2015: "0",
2016: "0",
carseries: "Bremen"
}];

输出应该是这样的:

var row = [{
2015: "95163",
carseries: "Sindelfingen"
},{
2014: "38954",
carseries: "Bremen"
}];

最佳答案

您需要使用数组迭代器的组合:map , filter , 和 reduce .

function clean(obj) {
return Object.keys(obj) // get own keys
.filter(function(key) { // keep non '0' values
return obj[key] !== '0'
})
.reduce(function(out, key) { // recreate object using filtered keys
out[key] = obj[key]

return out
}, {})
}

var row = [{
2013: "0",
2014: "0",
2015: "95163",
carseries: "Sindelfingen"
}, {
2013: "0",
2014: "38954",
2015: "0",
2016: "0",
carseries: "Bremen"
}];

// apply clean function to each element of initial array
console.log(row.map(clean))

关于javascript - 如果值为 0,则从数组中的对象中删除属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46071871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com