user91579631 user91579631 - 1 month ago 8
Node.js Question

Remove some properties from array of javascript objects

I would like to remove some properties from an array of javascript objects. Here is the array of objects.

obj_array = [{
"DATA_ID": 1,
"DATA_NAME": "Jim",
"DATA_BB_TYP": 2,
"DATA_MAC": "5474",
},
{
"DATA_ID": 3,
"DATA_NAME": "Fro",
"DATA_BB_TYP": 33,
"DATA_MAC": "8e30",
},
{
"DATA_ID": 2,
"DATA_NAME": "Jimb",
"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",
}
]


I have this string array which specifies what properties to remove.

var str_array_criteria = ["DATA_BB_TYP", "DATA_MAC"];


After removal, the array of object will look like this;

obj_array_removed = [{
"DATA_ID": 1,
"DATA_NAME": "Jim",
},
{
"DATA_ID": 3,
"DATA_NAME": "Fro",
},
{
"DATA_ID": 2,
"DATA_NAME": "Jimb",
},
{
"DATA_ID": 4,
"DATA_NAME": "Kht1",
},
{
"DATA_ID": 6,
"DATA_NAME": "Sens",
}
]


I am using node.js v6.

Answer

Here you go,

var obj_array = [{
        "DATA_ID": 1,
        "DATA_NAME": "Jim",
        "DATA_BB_TYP": 2,
        "DATA_MAC": "5474",
    },
    {
        "DATA_ID": 3,
        "DATA_NAME": "Fro",
        "DATA_BB_TYP": 33,
        "DATA_MAC": "8e30",
    },
    {
        "DATA_ID": 2,
        "DATA_NAME": "Jimb",
        "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 str_array_criteria = ["DATA_BB_TYP", "DATA_MAC"];

    var new_obj_array = obj_array.map(function(obj) {
      str_array_criteria.forEach(function(prop) {
        delete obj[prop];
      });
      
      return obj;
    });

    console.log(new_obj_array);