JavaScript保留某些属性并从对象数组中删除其他属性

时间:2016-11-06 04:01:08

标签: node.js javascript-objects

我想保留javascript对象数组中的一些属性。这是对象数组。

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_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",
    }
]

我正在使用node.js v6。

2 个答案:

答案 0 :(得分:1)

您可以使用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);




答案 1 :(得分:1)

使用Underscore,这只是

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