我有这样的JSON对象数组:
[ { id: 841,
when: 'date',
who: 'asd',
what: 'what',
key1 : 'a key',
key2 : 'a key'
_id: 544034ab914ae3b9270545c1,
__v: 0 },
{ id: 841,
when: 'date',
who: 'asd',
what: 'what',
key1 : 'a key',
key2 : 'a key'
_id: 544034ab914ae3b9270545c1,
__v: 0 } ]
我想从这些对象中剪切key1
和key2
,并希望看到这一点:
[ { id: 841,
when: 'date',
who: 'asd',
what: 'what',
_id: 544034ab914ae3b9270545c1,
__v: 0 },
{ id: 841,
when: 'date',
who: 'asd',
what: 'what',
_id: 544034ab914ae3b9270545c1,
__v: 0 } ]
如何剪切键和值?
我的方法不起作用。 (伪):
var new_array
for i old_array.length
delete old_array[i].key1
delete old_array[i].key2
new_array.push(old_array[i])
答案 0 :(得分:1)
yourArray = yourArray.map(function(current, index, arr){
delete current.key1;
delete current.key2;
return current;
});
那应该按你的意愿行事; - )
希望有所帮助, 扬
答案 1 :(得分:0)
您的伪代码基本上是您所需要的,但您可以只删除属性:
var arr = [...]; // your array
for (var i = 0; i < arr.length; i++) {
delete arr[i].key1;
delete arr[i].key2;
}
答案 2 :(得分:0)
像这样:
function deleteProps(){
var a = Array.slice(arguments) || Array.prototype.slice.call(arguments);
var oa = a[0], dp = a.slice(1);
for(var i=0,l=oa.length; i<l; i++){
for(var n=0,c=dp.length; n<c; n++){
delete oa[i][dp[n]];
}
}
return oa;
}
var newObjectsArray = deleteProps(objectsArray, 'key1', 'key2');
答案 3 :(得分:0)
我使用了underscore.js
var cutted_object = _.omit(json_object, "key1", "key2"
"key2", "date",
"id33", "etc");