Skip to content Skip to sidebar Skip to footer

Find By Key And Replace By Value In Nested Json Object

I have an json object It can be nested and I have an second object containing key/value pair. I want to replace the second object's value by first one by matching key both object's

Solution 1:

You could first save all references and then assign the data, you have.

functionupdate(object, data) {
    functiongetAllKeys(o) {
        Object.keys(o).forEach(function (k) {
            if (typeof o[k] === 'object') {
                returngetAllKeys(o[k]);
            }
            keys[k] = o;
        });
    }

    var keys = Object.create(null);

    getAllKeys(object);
    Object.keys(data).forEach(function (k) {
        if (keys[k] && k in keys[k]) { // check if key for update exist
            keys[k][k] = data[k];
        }
    });
}

var object = { "enquiry": { "Lead": { "SubLead": { "DealerRef": "test", "DealerFloor": "test", "Region": "test", "Source": { "Special": "test", "TestDrive": "test", "TradeIn": "test", "Finance": "test" } }, "Contact": { "Info": { "FirstName": "test", "Surname": "test", "Email": "test", "OfficePhone": "test", "CellPhone": "test" } }, "Seeks": { "Stock": { "Used": "test", "Brand": "test", "Model": "test", "StockNr": "test" } } } } },
    data = { DrNo: 666, DealerRef: '18M', DealerFloor: 'UCP', Region: 'Western Cape', FirstName: 'abc', Surname: 'xyz', Email: 'test@ctm.co.za', OfficePhone: '2343243', CellPhone: '2343243', Used: '1', Brand: 'QAE', Model: 'test', StockNr: 'SEDONA', Special: '2013 Kia Sedona', TestDrive: '0', TradeIn: '0', Finance: '0' };

update(object, data);

console.log(object);

Solution 2:

You can iterate through firstObj and replace key/value with secondObj

functioniterateObj(obj){
  for(var key in obj){
    if(obj.hasOwnProperty(key)){
      if(typeof obj[key] === 'object'){
        iterateObj(obj[key]);
      }
      elseif(secondObj[key]!=undefined){
        obj[key] = secondObj[key]
      }
    }
  }
}
iterateObj(firstObj)

console.log(firstObj); // this will give proper results

Post a Comment for "Find By Key And Replace By Value In Nested Json Object"