I used this code to find the required portion from the json object from sJhonny’s Question
Data Sample
JavaScript
x
43
43
1
TestObj = {
2
"Categories": [{
3
"Products": [{
4
"id": "a01",
5
"name": "Pine",
6
"description": "Short description of pine."
7
},
8
{
9
"id": "a02",
10
"name": "Birch",
11
"description": "Short description of birch."
12
},
13
{
14
"id": "a03",
15
"name": "Poplar",
16
"description": "Short description of poplar."
17
}],
18
"id": "A",
19
"title": "Cheap",
20
"description": "Short description of category A."
21
},
22
{
23
"Product": [{
24
"id": "b01",
25
"name": "Maple",
26
"description": "Short description of maple."
27
},
28
{
29
"id": "b02",
30
"name": "Oak",
31
"description": "Short description of oak."
32
},
33
{
34
"id": "b03",
35
"name": "Bamboo",
36
"description": "Short description of bamboo."
37
}],
38
"id": "B",
39
"title": "Moderate",
40
"description": "Short description of category B."
41
}]
42
};
43
Function to find
JavaScript
1
13
13
1
function getObjects(obj, key, val) {
2
var objects = [];
3
for (var i in obj) {
4
if (!obj.hasOwnProperty(i)) continue;
5
if (typeof obj[i] == 'object') {
6
objects = objects.concat(getObjects(obj[i], key, val));
7
} else if (i == key && obj[key] == val) {
8
objects.push(obj);
9
}
10
}
11
return objects;
12
}
13
Use like so:
JavaScript
1
2
1
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
2
This code is to select matching piece from the source. But what I want is to update the source object with new value and retrieve the updated source object.
I want something like
JavaScript
1
2
1
getObjects(TestObj, 'id', 'A', 'B'); // Returns source with updated value. (ie id:'A' updated to id:'B' in the returned object)
2
My code
JavaScript
1
14
14
1
function getObjects(obj, key, val, newVal) {
2
var newValue = newVal;
3
var objects = [];
4
for (var i in obj) {
5
if (!obj.hasOwnProperty(i)) continue;
6
if (typeof obj[i] == 'object') {
7
objects = objects.concat(getObjects(obj[i], key, val));
8
} else if (i == key && obj[key] == val) {
9
obj[key] = 'qwe';
10
}
11
}
12
return obj;
13
}
14
This works if i give obj[key] = 'qwe';
but if i change the code into obj[key] = newValue;
its updated as undefined.
Why is that so?
Advertisement
Answer
You forgot to pass newValue in the nested call
JavaScript
1
14
14
1
function getObjects(obj, key, val, newVal) {
2
var newValue = newVal;
3
var objects = [];
4
for (var i in obj) {
5
if (!obj.hasOwnProperty(i)) continue;
6
if (typeof obj[i] == 'object') {
7
objects = objects.concat(getObjects(obj[i], key, val, newValue));
8
} else if (i == key && obj[key] == val) {
9
obj[key] = 'qwe';
10
}
11
}
12
return obj;
13
}
14