如何解决JavaScript根据属性值过滤对象数组
您可以尝试以下方法1和2:
方法1 :(使用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);
解决方法
我在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_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",}
]
我想保留一些对象并删除其余的对象。如果object属性DATA_BB_TYP
为2或34,则将保留对象。其他对象被删除。obj_array
遗嘱的结果看起来像这样;
obj_array_retained =
[{
"DATA_ID": 1,}
]
我正在使用node.js v6.91。
编辑:有人建议我使用过滤器来解决这种问题。欢迎使用过滤器技术的答案。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。