我有一个ASP.Net隐藏字段,其中包含JSON格式的数据,如下所示
[
{
"RegionName": "USA",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "8888",
"Country": "USA",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Test",
"Email": "Test@test.com",
"Phone": "9998887777"
}
},
{
"RegionName": "Mexico",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "33333",
"Country": "Mexico",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Amex",
"Email": "test@test.com",
"Phone": "9998887777"
}
}
]
使用以下代码在Javascript中读取
var value = $('#countryInvoice')[0].defaultValue;
现在我想使用基于Region名称的javascript搜索这个JSON,并从隐藏字段中删除记录。所以我想删除美国的数据点,所以只有下面的
[
{
"RegionName": "Mexico",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "33333",
"Country": "Mexico",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Amex",
"Email": "test@test.com",
"Phone": "9998887777"
}
}
]
有人能告诉我如何在JQuery或Javascript中做到这一点吗。
感谢
//ES5
var res = value.filter(function(e) { return e["RegionName"] != "USA"; })
//ES6
var res = value.filter(e => e["RegionName"] != "USA")
注意:Arrow函数是ES6语法。
您只需要使用Array.prototype.filter()
过滤掉它。
查看此处的MDN文档
下面的片段过滤掉了美国
let value = [{
"RegionName": "USA",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "8888",
"Country": "USA",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Test",
"Email": "Test@test.com",
"Phone": "9998887777"
}
},
{
"RegionName": "Mexico",
"Contact": {
"LegalName": "somethinglegal",
"StreetAddress": "hello",
"City": "Test",
"State": "Test",
"Zip": "33333",
"Country": "Mexico",
"VAT": "VAT"
},
"EntityContact": {
"LegalName": "Amex",
"Email": "test@test.com",
"Phone": "9998887777"
}
}
];
let newArray = value.filter(arr => arr.RegionName !== 'USA');
console.log(newArray);