i want to replace 11111 to <, and 22222 to > in json
My code:
var json_A = {
"question1": {
"type": "string",
"title": "11111img src=`https://i.imgur.com/RQpTQBw.png`22222",
"enum": ["Adrian", "Attams", "Adrienne"],
"requested": false
},
"question2": {
"type": "string",
"title": "11111img src=`https://i.imgur.com/SHB02L8.png`22222",
"enum": ["She does.", "No.", "Yes"],
"requested": false
}
}
function replaceValueOfJson(json, field, oldvalue, newvalue) {
for (var k = 0; k < json.length; ++k) {
if (oldvalue == json[k][field]) {
json[k][field] = newvalue;
}
}
return json;
}
var string_format = replaceValueOfJson(json_A,'title','11111','aaaaa')
//alert(string_format)
console.log(string_format)
My desired output:
{
"question1": {
"type": "string",
"title": "<img src=`https://i.imgur.com/RQpTQBw.png`>",
"enum": ["Adrian", "Attams", "Adrienne"],
"requested": false
},
"question2": {
"type": "string",
"title": "<img src=`https://i.imgur.com/SHB02L8.png`>",
"enum": ["She does.", "No.", "Yes"],
"requested": false
}
}
Related topic: how to change json key:value
How can i change above function to get correct output?
4
Answers
JavaScript objects don’t have a
length
property. (Unless you manually add one)Instead, you can iterate over
Object.values()
and executeString#replace()
on the field of your choice like this:Object.values()
returns an array of the values in the object passed through it.Just indent json and you’ll see the problem:
Still don’t see it ? here:
Linear iterating an hierarchical structure won’t do any good. You have to consider json levels.
Recursive solution (will modify the original object):
Try it: