node.js - JavaScript Retain certain properties and remove other properties from array of objects -
i retain properties array of javascript objects. here array of objects.
obj_array = [{ "chr_id": 1, "chr_name": "jim", "chr_bb_typ": 2, "chr_mac": "5474", }, { "chr_id": 3, "chr_name": "fro", "chr_bb_typ": 33, "chr_mac": "8e30", }, { "chr_id": 2, "chr_name": "jimb", "chr_bb_typ": 2, "chr_mac": "45e8", }, { "chr_id": 4, "chr_name": "kht1", "chr_bb_typ": 35, "chr_mac": "58d0", }, { "chr_id": 6, "chr_name": "sens", "chr_bb_typ": 34, "chr_mac": "d004", } ]
i have string array specifies properties retain.
var str_array_criteria = ["chr_id", "chr_name"];
after removal, array of object this;
obj_array_removed = [{ "chr_id": 1, "chr_name": "jim", }, { "chr_id": 3, "chr_name": "fro", }, { "chr_id": 2, "chr_name": "jimb", }, { "chr_id": 4, "chr_name": "kht1", }, { "chr_id": 6, "chr_name": "sens", } ]
i using node.js v6.
here go object.keys
,
var obj_array = [{ "chr_id": 1, "chr_name": "jim", "chr_bb_typ": 2, "chr_mac": "5474", }, { "chr_id": 3, "chr_name": "fro", "chr_bb_typ": 33, "chr_mac": "8e30", }, { "chr_id": 2, "chr_name": "jimb", "chr_bb_typ": 2, "chr_mac": "45e8", }, { "chr_id": 4, "chr_name": "kht1", "chr_bb_typ": 35, "chr_mac": "58d0", }, { "chr_id": 6, "chr_name": "sens", "chr_bb_typ": 34, "chr_mac": "d004", } ]; var str_array_criteria = ["chr_id", "chr_name"]; obj_array.foreach(function(obj) { object.keys(obj).foreach(function(key){ if(str_array_criteria.indexof(key) === -1) { delete obj[key]; } }); }); //var new_obj_array = obj_array.map(function(obj) { //object.keys(obj).foreach(function(key){ //if(str_array_criteria.indexof(key) === -1) { //delete obj[key]; //} //}); //return obj; //}); console.log(obj_array);
Comments
Post a Comment