Updating a JSON object using Javascript

前端 未结 9 1560
Happy的楠姐
Happy的楠姐 2020-12-07 13:37

How can i update the following JSON object dynamically using javascript or Jquery?

var jsonObj = [{\'Id\':\'1\',\'Username\':\'Ray\',\'FatherName\':\'Thompso         


        
9条回答
  •  天涯浪人
    2020-12-07 14:14

    I took Michael Berkowski's answer a step (or two) farther and created a more flexible function allowing any lookup field and any target field. For fun I threw splat (*) capability in there incase someone might want to do a replace all. jQuery is NOT needed. checkAllRows allows the option to break from the search on found for performance or the previously mentioned replace all.

    function setVal(update) {
        /* Included to show an option if you care to use jQuery  
        var defaults = { jsonRS: null, lookupField: null, lookupKey: null,
            targetField: null, targetData: null, checkAllRows: false }; 
        //update = $.extend({}, defaults, update); */
    
        for (var i = 0; i < update.jsonRS.length; i++) {
            if (update.jsonRS[i][update.lookupField] === update.lookupKey || update.lookupKey === '*') {
                update.jsonRS[i][update.targetField] = update.targetData;
                if (!update.checkAllRows) { return; }
            }
        }
    }
    
    
    var jsonObj = [{'Id':'1','Username':'Ray','FatherName':'Thompson'},  
               {'Id':'2','Username':'Steve','FatherName':'Johnson'},
               {'Id':'3','Username':'Albert','FatherName':'Einstein'}]
    

    With your data you would use like:

    var update = {
        jsonRS: jsonObj,
        lookupField: "Id",
        lookupKey: 2, 
        targetField: "Username",
        targetData: "Thomas", 
        checkAllRows: false
        };
    
    setVal(update);
    

    And Bob's your Uncle. :) [Works great]

提交回复
热议问题