How To Update Json Object Value Dynamically In Jquery?
var jsonObj = [ { 'key1': 'value1', 'key2': 'value2', 'key3': 'value3' }, { 'key1': 'value1', 'key2': 'value2', 'key
Solution 1:
jsonObj
is an array thus you first have to iterate this array
jsonObj.forEach(o => {...});
o
is now an object. You have to iterate the keys/values of it
for(let k in o)
k
is a key in the object. You can now alter the value
o[k] = 'WhateverYouNeed'
var jsonObj = [{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}];
jsonObj.forEach(o => {
for(let k in o)
o[k] = 'ChangedValue'
});
console.log(jsonObj);
References:
As stated, your structure is an array of objects and not JSON: Javascript object Vs JSON
Now breaking you problem into parts, you need to
- Update property of an object: How to set a Javascript object values dynamically?
- But you need to update them all: How do I loop through or enumerate a JavaScript object?
- But these objects are inside an array: Loop through an array in JavaScript
- But why do I have different mechanism to loop for Objects and Arrays?
for
cannot get keys but we can usefor..in
over arrays. Right? No, you should not. Why is using "for...in" with array iteration a bad idea?
ReadMe links:
Please refer following link and check browser compatibility as the solution will not work in older browsers. There are other ways to loop which are highlighted in above link. Refer compatibility for them as well before using them.
Solution 2:
Here you go with a solution https://jsfiddle.net/Lha8xk34/
var jsonObj = [{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}, {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}];
$.each(jsonObj, function(i) {
$.each(jsonObj[i], function(key) {
jsonObj[i][key] = "changed" + key;
});
});
console.log(jsonObj);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Solution 3:
You might want to use a mixture of forEach
and Object.keys
const jsonObj = [
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
];
jsonObj.forEach( obj => {
Object.keys( obj ).forEach( key => {
const value = obj[ key ];
console.log( key, value );
} );
} );
Solution 4:
Try pinch
in your Case :
var jsonObj = [
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
];
pinch(data, "/key1/", function(path, key, value) {
return (value === "value1") ? "updatedValue" : value;
});
Post a Comment for "How To Update Json Object Value Dynamically In Jquery?"