并从对象数组中删除其他属性

并从对象数组中删除其他属性

本文介绍了JavaScript保留某些属性,并从对象数组中删除其他属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我正在使用node.js v6.

I am using node.js v6.

推荐答案

在这里,您选择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);

这篇关于JavaScript保留某些属性,并从对象数组中删除其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:24