user91579631 user91579631 - 29 days ago 8
Node.js Question

Retain certain properties from array of objects

I would like to retain some properties from an array of javascript objects. Here is the 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 this string array which specifies what properties to retain.

var str_array_criteria = ["CHR_ID", "CHR_NAME"];


After removal, the array of object will look like 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 am using node.js v6.

Answer

Here you go with 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"];

    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(new_obj_array);

Comments