how to change json key:value

后端 未结 4 1005
面向向阳花
面向向阳花 2020-12-29 00:01
//my json data    
var jsndata = \"{ \"id\": \"5001\", \"type\": \"None\" },
            { \"id\": \"5002\", \"type\": \"Glazed\" },
            { \"id\": \"5005\",          


        
4条回答
  •  一整个雨季
    2020-12-29 00:14

    modified the function from above to be able to change all values of a key,and increment it by 1. And you can pass in the jsonObj

    function replaceByValue( jsonObj, field, oldvalue, newvalue ) {
        for( var k = 0; k < jsonObj.length; ++k ) {
                 jsonObj[k][field] = (newvalue *1)+k;
    
        }
        return jsonObj;
    }
    

    //example

    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" }]; 
    
    
    json; 
    
    replaceByValue( json, "id", "na", 123 );
    
    json;
    

提交回复
热议问题