我在Javascript中使用Spring Framework和angular JS。 和AJAX请求成功。 但我有一个问题是删除一些键和值。 我的代码是
$.ajax({
type: 'POST',
dataType: 'JSON',
data: JSON.stringify(search),
contentType:"application/json; charset=UTF-8",
url: '/yboard/select',
error: function() {
alert("Loading failed!");
},
success: function(returnJSON) {
if (returnJSON.success) {
var result = JSON.stringify(returnJSON.items);
console.log("no : " + result);
} else {
alert("it's failed");
}
}
});
输出
no : [{"boardID":"9b5199799c908e48051e2e131f2d35cc","no":204,"capital_stock":"","pno_stock":"3204000336","pname_stock":"HEATER","storage_code_stock":"C03","storage_name_stock":"A","price_indicator_stock":"M","unit_stock":"EA","stock_amount_stock":"12.00","tracking_no_stock":"015","standard_stock":"WATLOW: SFRE","client_code_stock":"1193","client_name_stock":"aaa","priority_stock":0},{"boardID":"6a11d21aa400ff6c94d7d7a21b762433","no":203,"capital_stock":"","pno_stock":"3204000328","pname_stock":"HEATER","storage_code_stock":"C03","storage_name_stock":"A","price_indicator_stock":"M","unit_stock":"EA","stock_amount_stock":"12.00","tracking_no_stock":"015","standard_stock":"SFRE","client_code_stock":"1153","client_name_stock":"bbb","priority_stock":0}]
我试图移除' boardID'和' priority_stock'这段代码的密钥。
delete returnJSON.items['boardID']
delete returnJSON.items['priority_stock']
或
delete result['boardID']
delete result['priority_stock']
但未能删除。 问题是什么?
答案 0 :(得分:1)
returnJSON
对象的boardID
属性是一个数组。您有两个项目,因此,如果您想从两者中删除priority_stock
和for (var i = 0; i < returnJSON.items.length; i++) {
delete returnJSON.items[i].boardID;
delete returnJSON.items[i].priority_stock;
}
,则需要循环覆盖您的项目并逐个删除每个密钥,如下所示:
xib
答案 1 :(得分:1)
删除所有项目的键
returnJSON.items.forEach(function(x){ delete x['boardID'] });
returnJSON.items.forEach(function(x){ delete x['priority_stock'] });
答案 2 :(得分:1)
您可以将ES6 Array Map方法与Arrow函数表达式一起使用。
工作演示
let returnJSON= {
"items": [{
"boardID": "9b5199799c908e48051e2e131f2d35cc",
"no": 204,
"capital_stock": "",
"pno_stock": "3204000336",
"pname_stock": "HEATER",
"storage_code_stock": "C03",
"storage_name_stock": "A",
"price_indicator_stock": "M",
"unit_stock": "EA",
"stock_amount_stock": "12.00",
"tracking_no_stock": "015",
"standard_stock": "WATLOW: SFRE",
"client_code_stock": "1193",
"client_name_stock": "aaa",
"priority_stock": 0
}, {
"boardID": "6a11d21aa400ff6c94d7d7a21b762433",
"no": 203,
"capital_stock": "",
"pno_stock": "3204000328",
"pname_stock": "HEATER",
"storage_code_stock": "C03",
"storage_name_stock": "A",
"price_indicator_stock": "M",
"unit_stock": "EA",
"stock_amount_stock": "12.00",
"tracking_no_stock": "015",
"standard_stock": "SFRE",
"client_code_stock": "1153",
"client_name_stock": "bbb",
"priority_stock": 0
}]
};
var res = returnJSON.items.map(obj => {
(obj.hasOwnProperty('boardID')) ? delete obj.boardID : '';
(obj.hasOwnProperty('priority_stock')) ? delete obj.priority_stock : '';
return obj;
});
console.log(res);