Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change json key:value

Tags:

json

replace

set

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

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 ?

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

Will jsndata.id['5003']='1234' change it?

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

like image 769
NovaYear Avatar asked Dec 29 '10 10:12

NovaYear


1 Answers

<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>
like image 114
St.Woland Avatar answered Oct 07 '22 09:10

St.Woland