Javascript - 遍历深度嵌套对象并更改某些未知值

11

我有一个包含未知层数和类型(数组,对象,字符串)的对象,这里是一个例子:

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

我需要使用普通的JavaScript循环遍历每个属性,并对每个包含单引号的字符串进行清理以将其替换为''(用于在PostGres查询中使用),我使用以下代码进行更改:

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

我可以通过循环该对象并使用以下代码将它们显示出来,虽然这可能不是最好的解决方案:

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);
问题在于我不知道如何实际进行清理部分并更新原始数据数组,因为这是在循环中进行的。
我发现有很多人提出了类似的问题,但是无法完全将他们的答案用于我的情况。
感激任何帮助。

你确定需要这个吗?可能你正在使用的库已经内置了一些清理逻辑。 - eltonkamami
那么这个:8\'x10\' 应该变成 8\"x10\" 吗? - KevBot
是的,不幸的是。 - Mankind1023
3个回答

27

你可以检查一个对象,然后再次调用递归。

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


5
为什么不将整个对象转换为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);


这是一个有趣的模式!只要你确保用 replace 不会破坏 JSON,它就非常简单。 - For the Name

4

尝试使用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接