如何删除对象数组中首个动态key值为空的对应元素?
实现逻辑
- 使用JS原生数组方法
filter对原数组做过滤,无需手动遍历删除元素,避免出现数组塌陷问题 - 对每个对象通过
Object.keys(item)[0]直接获取首个动态key,无需提前枚举所有可能的key值 - 仅保留首个动态key取值非空的对象,自动过滤不符合要求的元素
可直接运行的代码
var arr = [ {qty_auth: "", resolution: "4", status: "", order: "1495"}, {qty_sized: "1", resolution: "4", status: "", order: "1485"} ] // 核心过滤代码,兼容所有主流浏览器 arr = arr.filter(function(item) { const firstDynamicKey = Object.keys(item)[0] return item[firstDynamicKey] !== "" }) /* 输出结果: [ {qty_sized: "1", resolution: "4", status: "", order: "1485"} ] */
如果是现代前端项目用ES6+语法,可以把过滤逻辑简化为箭头函数写法:
arr = arr.filter(item => item[Object.keys(item)[0]] !== "")
内容的提问来源于stack exchange,提问作者Shantal Kaula
相关产品推荐
相关产品推荐

