如何更改 json 键:值 [英] how to change json key:value

查看:19
本文介绍了如何更改 json 键:值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//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"

How would i change "type": "Chocolate" => "type": "only water"
or.. "id": "5005" => "id": "1234"

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

My list is very long.. I need get or set any value ?

注意:我的列表是动态的,并且总是按 id 或类型排序..

Note: My list is dynamic and always sorting order by id or type..

jsndata.id['5003']='1234'会改吗?

var getval = jsndata.id['5005'].type get val..(value Sugar) ?

var getval = jsndata.id['5005'].type get val..(value Sugar) ?

推荐答案

<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 键:值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆