ich diesen Code verwendet, um den gewünschten Teil aus dem JSON-Objekt aus sJhonny's Questionzu Finden und Update in verschachtelte JSON-Objekt
Datenabtastblock
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."
}]
};
Funktion zu finden
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;
}
Verwendung zu finden, wie so:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
Dieser Code dient zur Auswahl eines übereinstimmenden Stücks aus der Quelle. Aber ich möchte das Quellobjekt mit einem neuen Wert aktualisieren und das aktualisierte Quellobjekt abrufen.
Ich möchte so etwas wie
getObjects(TestObj, 'id', 'A', 'B'); // Returns source with updated value. (ie id:'A' updated to id:'B' in the returned object)
Mein Code
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;
}
Dies funktioniert, wenn ich obj[key] = 'qwe';
geben, aber wenn ich den Code in obj[key] = newValue;
seine als undefiniert aktualisiert ändern.
Warum ist das so?
obj [key] = newVal passieren? – Virus721
in sonst wenn Bedingung richtig? – Okky
Ich verstehe nicht, was Sie tun möchten. Möchten Sie das Quellobjekt gleichzeitig mit dem Abrufen eines Teils aktualisieren? oO – Virus721