JavaScript Retain certain properties and remove other properties from array of objects

纵饮孤独 提交于 2019-12-13 07:18:44

问题


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.


回答1:


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"];

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



回答2:


With Underscore, this would just be

_.map(obj_array, elt => _.pick(elt, ...str_array_criteria))


来源:https://stackoverflow.com/questions/40445853/javascript-retain-certain-properties-and-remove-other-properties-from-array-of-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!