Znajdź i zaktualizuj zagnieżdżony obiekt json

Użyłem tego kodu, aby znaleźć wymaganą część z obiektu jsonPytanie Jhonnego

Próbka danych

TestObj = {
    "Categories": [{
        "Products": [{
            "id": "a01",
            "name": "Pine",
            "description": "Short description of pine."
        },
        {
            "id": "a02",
            "name": "Birch",
            "description": "Short description of birch."
        },
        {
            "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."
    }]
};

Funkcja do znalezienia

function getObjects(obj, key, val) {
    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));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}

Użyj w ten sposób:

getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects

Ten kod służy do wybierania pasującego fragmentu ze źródła. Chcę jednak zaktualizować obiekt źródłowy o nową wartość i pobrać zaktualizowany obiekt źródłowy.

Chcę coś takiego

getObjects(TestObj, 'id', 'A', 'B'); // Returns source with updated value. (ie id:'A' updated to id:'B' in the returned object)

Mój kod

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));
        } else if (i == key && obj[key] == val) {
            obj[key] = 'qwe';
        }
    }
    return obj;
}

To działa, jeśli damobj[key] = 'qwe'; ale jeśli zmienię kod naobj[key] = newValue; jego aktualizacja jako niezdefiniowana.

Dlaczego to jest takie?

questionAnswers(3)

yourAnswerToTheQuestion