过滤数组以获取对象键的子集

时间:2015-02-03 23:31:04

标签: javascript grep

假设我有:

var JSONArray = [{'key1':'a1','key2':'a2','key3':'a3'},
                 {'key1':'b1','key2':'b2','key3':'b3'},
                 etc 
                ];

如何获得一个包含相同对象的数组,但没有'key3'

4 个答案:

答案 0 :(得分:1)

underscore.js可能有用。

  

Underscore是一个JavaScript库,它提供了大量有用的函数式编程助手,而无需扩展任何内置对象。

var JSONArray = [
    {'key1':'a1','key2':'a2','key3':'a3'},
    {'key1':'b1','key2':'b2','key3':'b3'}
];

_.map(JSONArray, function (x) { return _.omit(x, 'key3') });
=> [{'key1':'a1','key2':'a2'}, {'key1':'b1','key2':'b2'}]

工作sample

答案 1 :(得分:0)

您可以浏览数组并删除密钥为'key3'的每个键值对:

for (var i = 0; i < JSONArray.length; i++) {
  delete JSONArray[i]['key3'];
}

JSONArray现在将成为:

[
  {key1: "a1", key2: "a2"},
  {key1: "b1", key2: "b2"}
];

答案 2 :(得分:0)

也许使用map并减少?

var JSONArray = [{'key1':'a1','key2':'a2','key3':'a3'},
                 {'key1':'b1','key2':'b2','key3':'b3'}
                ];

JSONArray.map(function(obj){
  return Object.keys(obj).reduce(function(filtered, curr){
    if(curr !== 'key3'){
      filtered[curr] = obj[curr];
    }
    return filtered;
  }, {});
});

答案 3 :(得分:0)

var JSONArray = [{'key1':'a1','key2':'a2','key3':'a3'},
                 {'key1':'b1','key2':'b2','key3':'b3'}];

1. You can remove the values from the objects in the array:

JSONArray.forEach(function(itm){
    delete itm.key3;
});


new value of JSONArray:    
[{"key1":"a1","key2":"a2"},{"key1":"b1","key2":"b2"}]


2. or you can clone a new array of new objects-

var nokey3= 
JSON.parse(JSON.stringify(JSONArray));
nokey3.forEach(function(itm){
    delete itm.key3;
});


value of JSONArray:
[{"key1":"a1","key2":"a2","key3":"a3"},
{"key1":"b1","key2":"b2","key3":"b3"}]

value of nokey3:

[{"key1":"a1","key2":"a2"},{"key1":"b1","key2":"b2"}]