gpt4 book ai didi

json - 如何更改json key :value

转载 作者:行者123 更新时间:2023-12-02 05:01:14 24 4
gpt4 key购买 nike

//my json data    
var jsndata = "{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" },
{ "id": "5009", "type": "Juice" }"

我该如何改变"type": "Chocolate" => "type": "only water"
或.."id": "5005" => "id": "1234"

我的列表很长..我需要获取或设置任何值吗?

注意:我的列表是动态的,并且始终按 ID 或类型排序。

威尔jsndata.id['5003']='1234'改变它吗?

var getval = jsndata.id['5005'].type获取 val..(糖值)?

最佳答案

<script>
var json = [{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" },
{ "id": "5009", "type": "Juice" }];
/**
* The function searches over the array by certain field value,
* and replaces occurences with the parameter provided.
*
* @param string field Name of the object field to compare
* @param string oldvalue Value to compare against
* @param string newvalue Value to replace mathes with
*/
function replaceByValue( field, oldvalue, newvalue ) {
for( var k = 0; k < json.length; ++k ) {
if( oldvalue == json[k][field] ) {
json[k][field] = newvalue ;
}
}
return json;
}

/**
* Let's test
*/
console.log(json);

replaceByValue('id','5001','5010')
console.log(json);

replaceByValue('type','Chocolate','only water')
console.log(json);
</script>

关于json - 如何更改json key :value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4553235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com