我在asp.net的hiddenfield中有下一个文本,这个值是Json序列化
text = "[{ "Element":"E001", "City":"Madrid", "Country":"Spain"},
{ "Element":"E003", "City":"Paris", "Country":"Italy"},
{ "Element":"A001", "City":"Pekin", "Country":"China"}]
我想改变像这样的
这样的JS函数的元素的值function ModificarDato(jsonelemento, jsonvalor)
{
var vjson = eval($("[ id$='H_Ins").val());
var vjson2 = `$`(jQuery.parseJSON(JSON.stringify(vjson))).each(function ()
{
var vElemento = this.Element;
var vCity = this.City;
var vValor = this.Country;
if (vElemento == jsonelemento)
{
this.Country = jsonvalor;
}
});
var jsonvalorfinal = JSON.stringify(vjson2);
alert("Valor final : " + jsonvalorfinal);
$("[ id$='H_Ins").val(jsonvalorfinal);
}
问题在于,当我将jsonvalorfinal放入隐藏字段时,文本是不同的
text = "{"0":{"Element":"E001", "City":"Madrid", "Country":"Spain"},
"1":{"Element":"E003", "City":"Paris", "Country":"France"},
"2":{"Element":"A003", "City":"Pekin", "Country":"China"},
"length":3}
我需要相同格式的第一个字符串才能继续使用另一个函数。它可能
由于
答案 0 :(得分:0)
您可以按照以下方式执行此操作,您可以找到要更新的对象的索引并更新其国家/地区属性。
function ModifyData(element, newCountryValue) {
let text = `[
{
"Element": "E001",
"City": "Madrid",
"Country": "Spain"
},
{
"Element": "E003",
"City": "Paris",
"Country": "Italy"
},
{
"Element": "A001",
"City": "Pekin",
"Country": "China"
}
]`;
let parsedArray = JSON.parse(text);
let indexToBeModified = parsedArray.findIndex(item => item.Element == element);
parsedArray[indexToBeModified].Country = newCountryValue;
return parsedArray;
}
let modifiedArray = JSON.stringify(ModifyData("E001", "United States"), null, 4);
$("[ id$='H_Ins").val(modifiedArray);