Javascript - Iterate over deep nested object and change certain unknown values
Why not convert the entire object to JSON, and then replace all '
's with a "
? Then, you simplify the entire operation, without doing recursion.
var data = {ffs: false, customer: {customer_id: 1544248, z_cx_id: '123456',}, selected_items: {'3600196': [{id: 4122652, name: 'Essential Large (up to 8\'x10\')', selected: true}]}, service_partner: {id: 3486, name: 'Some String', street: '1234 King St.',}, subject: 'Project-2810191 - Orange Juice Stain (Rug)', description: 'Product Type: \n\nIssue: (copy/paste service request details here)\n\nAction Required:',};
data = JSON.stringify(data);
// or replace with two ' or whatever else
data = data.replace(/'/g, '\\"');
data = JSON.parse(data);
console.log(data);
You could check for an object and call the recursion again.
function iter(o) {
Object.keys(o).forEach(function (k) {
if (o[k] !== null && typeof o[k] === 'object') {
iter(o[k]);
return;
}
if (typeof o[k] === 'string') {
o[k] = o[k].replace(/'/g, "''");
}
});
}
var data = { ffs: false, customer: { customer_id: 1544248, z_cx_id: '123456' }, selected_items: { '3600196': [{ id: 4122652, name: 'Essential Large (up to 8\'x10\')', selected: true }] }, service_partner: { id: 3486, name: 'Some String', street: '1234 King St.' }, subject: 'Project-2810191 - Orange Juice Stain (Rug)', description: 'Product Type: \n\nIssue: (copy/paste service request details here)\n\nAction Required:' };
iter(data);
console.log(data);
try using the reviver method to avoid accidentally breaking your JSON structure.
var data = {ffs: false, customer: {customer_id: 1544248, z_cx_id: '123456',}, selected_items: {'3600196': [{id: 4122652, name: 'Essential Large (up to 8\'x10\')', selected: true}]}, service_partner: {id: 3486, name: 'Some String', street: '1234 King St.',}, subject: 'Project-2810191 - Orange Juice Stain (Rug)', description: 'Product Type: \n\nIssue: (copy/paste service request details here)\n\nAction Required:',};
data = JSON.stringify(data);
data = JSON.parse(data, (key, value) => {
return typeof value === 'string' ? value.replace(/'/g, '\\"') : value;
});
console.log(data);