JavaScript 根据属性值过滤对象数组
Posted
技术标签:
【中文标题】JavaScript 根据属性值过滤对象数组【英文标题】:JavaScript filter array of objects based on property values 【发布时间】:2017-03-19 06:03:04 【问题描述】:我在 javascript 中有一个对象数组。内容是这样的;
obj_array = [
"DATA_ID": 1,
"DATA_NAME": "Dim",
"DATA_BB_TYP": 2,
"DATA_MAC": "5474",
,
"DATA_ID": 3,
"DATA_NAME": "Spre",
"DATA_BB_TYP": 33,
"DATA_MAC": "8e30",
,
"DATA_ID": 2,
"DATA_NAME": "Dimb",
"DATA_BB_TYP": 2,
"DATA_MAC": "45e8",
,
"DATA_ID": 4,
"DATA_NAME": "Kht1",
"DATA_BB_TYP": 35,
"DATA_MAC": "58d0",
,
"DATA_ID": 6,
"DATA_NAME": "Sens",
"DATA_BB_TYP": 34,
"DATA_MAC": "d004",
]
我想保留一些对象并删除其余的。如果对象属性DATA_BB_TYP
为 2 或 34,则将保留对象。其他对象被删除。 obj_array
的结果将如下所示;
obj_array_retained =
[
"DATA_ID": 1,
"DATA_NAME": "Dim",
"DATA_BB_TYP": 2,
"DATA_MAC": "5474",
,
"DATA_ID": 2,
"DATA_NAME": "Dimb",
"DATA_BB_TYP": 2,
"DATA_MAC": "45e8",
,
"DATA_ID": 6,
"DATA_NAME": "Sens",
"DATA_BB_TYP": 34,
"DATA_MAC": "d004",
]
我正在使用 node.js v6.91。
编辑:有人建议我使用过滤器来解决这类问题。使用过滤技术的答案将是最受欢迎的。
【问题讨论】:
【参考方案1】:您可以尝试以下方法1和2:
方法一:(使用filter
)
注意:这将返回一个新数组,不会修改原始数组。
var obj_array = [
"DATA_ID": 1,
"DATA_NAME": "Dim",
"DATA_BB_TYP": 2,
"DATA_MAC": "5474",
,
"DATA_ID": 3,
"DATA_NAME": "Spre",
"DATA_BB_TYP": 33,
"DATA_MAC": "8e30",
,
"DATA_ID": 2,
"DATA_NAME": "Dimb",
"DATA_BB_TYP": 2,
"DATA_MAC": "45e8",
,
"DATA_ID": 4,
"DATA_NAME": "Kht1",
"DATA_BB_TYP": 35,
"DATA_MAC": "58d0",
,
"DATA_ID": 6,
"DATA_NAME": "Sens",
"DATA_BB_TYP": 34,
"DATA_MAC": "d004",
];
var retained = [2, 34];
var new_obj_array = obj_array.filter(function(obj)
if(retained.indexOf(obj.DATA_BB_TYP) === -1)
return false;
return true;
);
console.log(new_obj_array);
方法2:(如果你打算在浏览器中使用基本版本,因为旧浏览器不支持filter
)
var obj_array = [
"DATA_ID": 1,
"DATA_NAME": "Dim",
"DATA_BB_TYP": 2,
"DATA_MAC": "5474",
,
"DATA_ID": 3,
"DATA_NAME": "Spre",
"DATA_BB_TYP": 33,
"DATA_MAC": "8e30",
,
"DATA_ID": 2,
"DATA_NAME": "Dimb",
"DATA_BB_TYP": 2,
"DATA_MAC": "45e8",
,
"DATA_ID": 4,
"DATA_NAME": "Kht1",
"DATA_BB_TYP": 35,
"DATA_MAC": "58d0",
,
"DATA_ID": 6,
"DATA_NAME": "Sens",
"DATA_BB_TYP": 34,
"DATA_MAC": "d004",
];
var retained = [2, 34];
for(var i = obj_array.length - 1; i >= 0; i--)
var obj = obj_array[i];
if(retained.indexOf(obj.DATA_BB_TYP) === -1)
obj_array.splice(i, 1);
console.log(obj_array);
【讨论】:
谢谢。它完美地工作。赞成。有人建议我使用过滤器。你会不会碰巧知道如何使用过滤器来解决这个问题? 我已经用filter
更新了代码。请看一下
太棒了。它确实看起来更好。以上是关于JavaScript 根据属性值过滤对象数组的主要内容,如果未能解决你的问题,请参考以下文章