在嵌套的json对象中查找和更新,而不更改不同子路径中的相同键对值

Okk*_*kky 2 javascript jquery json jquery-selectors

这是对我之前的问题的更新在嵌套的json对象中查找和更新

样本数据

TestObj = {
    "Categories": [{
        "Products": [{
            "id": "a01",
            "name": "Pine",
            "description": "Short description of pine."
        },
        {
            "id": "a02",
            "name": "Pine",
            "description": "Short description of pine."
        },
        {
            "id": "a03",
            "name": "Poplar",
            "description": "Short description of poplar."
        }],
        "id": "A",
        "title": "Cheap",
        "description": "Short description of category A."
    },
    {
        "Product": [{
            "id": "b01",
            "name": "Maple",
            "description": "Short description of maple."
        },
        {
            "id": "b02",
            "name": "Oak",
            "description": "Short description of oak."
        },
        {
            "id": "b03",
            "name": "Bamboo",
            "description": "Short description of bamboo."
        }],
        "id": "B",
        "title": "Moderate",
        "description": "Short description of category B."
    }]
};
Run Code Online (Sandbox Code Playgroud)

我的功能

function getObjects(obj, key, val, newVal) {
    var newValue = newVal;
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val, newValue));
        } else if (i == key && obj[key] == val) {
            obj[key] = newValue;
        }
    }
    return obj;
}
Run Code Online (Sandbox Code Playgroud)

叫做

getObjects(TestObj, 'id', 'A', 'B');
Run Code Online (Sandbox Code Playgroud)

如果我要更新id,它工作正常; 因为id没有重复.但是,如果我正在更新名称,则更新匹配键值对的所有数据.但是如何将其约束为特定的密钥对值.

我应该为函数提供什么来约束更新范围以及如何实现它.请帮我.

注意:我将动态生成的json将动态生成,因此函数中不能有任何硬编码值

zs2*_*020 5

我想你可以以某种方式使用路径来定位值,然后进行更新.我从这篇文章中得到了这个想法.(@shesek回答)

var getPath = function (obj, path, newValue) {
    var parts = path.split('.');
    while (parts.length > 1 && (obj = obj[parts.shift()]));
    obj[parts.shift()] = newValue;
    return obj;
}

console.log(getPath(TestObj, 'Categories.0.Products.1.id', 'AAA'))
console.log(TestObj)
Run Code Online (Sandbox Code Playgroud)

所以你可以传入路径到对象,例如,如果你想id将下面的对象更新为"AAA",你可以传入Categories.0.Products.1.id

    {
        "id": "a02",
        "name": "Pine",
        "description": "Short description of pine."
    }
Run Code Online (Sandbox Code Playgroud)

然后,对象将成为

    {
        "id": "AAA",
        "name": "Pine",
        "description": "Short description of pine."
    }
Run Code Online (Sandbox Code Playgroud)

希望它能有所启发!