我在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。
编辑:有人建议使用过滤器来解决这类问题。使用过滤技术的答案将是最受欢迎的。答案 0 :(得分:5)
您可以尝试以下方法1和2:
方法1 :(使用override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Timer.scheduledTimer(timeInterval: 7.0, target: self, selector: #selector(functionOne), userInfo: nil, repeats: true)
}
func functionOne () {
print("hello")
}
)
注意:这将返回一个新数组,不会修改原始数组。
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
...
方法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);