简体   繁体   English

Javascript - 迭代深层嵌套对象并更改某些未知值

[英]Javascript - Iterate over deep nested object and change certain unknown values

I have an object with an unknown number of levels and types (array, object, string), here is an example:我有一个具有未知数量和类型(数组、对象、字符串)的对象,这是一个示例:

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:',
}

I have to loop through every property using plain javascript and sanitize each string that has a ' to have '' (for use in a PostGres Query), I change it with the following code:我必须使用普通的 javascript 遍历每个属性并清理每个带有 ' 到 '' 的字符串(用于 PostGres 查询),我使用以下代码对其进行更改:

val = val.replace(/'/g, "''");

And I can loop through the object and display them with this, although this may not be the best solution:我可以遍历对象并用这个显示它们,尽管这可能不是最好的解决方案:

function iterObj(obj) {
  for (var key in obj) {
    console.log(key + ': ' + obj[key]);
    if (obj[key] !== null && typeof obj[key] === "object") {
      // Recurse into children
      iterObj(obj[key]);
    }
  }
}

iterObj(data);

The problem is that I don't know how to actually do the sanitization part and update the original data array since this is going in circles.问题是我不知道如何实际执行清理部分并更新原始数据数组,因为这是循环往复。

I found plenty of people asking similar questions but couldn't quite get their answers to work in my case.我发现很多人都在问类似的问题,但在我的情况下无法得到他们的答案。

Any help is appreciated.任何帮助表示赞赏。

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);

Why not convert the entire object to JSON, and then replace all ' 's with a " ? Then, you simplify the entire operation, without doing recursion.为什么不将整个对象转换为 JSON,然后将所有' ' 替换为" ?然后,您可以简化整个操作,而无需进行递归。

 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);

try using the reviver method to avoid accidentally breaking your JSON structure.尝试使用reviver方法以避免意外破坏您的 JSON 结构。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM