为对象键的子集过滤数组

Filter an array for a subset of object keys

假设我有:

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

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

underscore.js 可能会有用。

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.

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

您可以遍历数组并删除键为 'key3':

的每个键值对
for (var i = 0; i < JSONArray.length; i++) {
  delete JSONArray[i]['key3'];
}

JSONArray 现在将是:

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

也许使用 map 和 reduce?

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