I have an object with multiple nested objects in it, it can also have array of objects. Here's an example:
{
"name": "0040",
"id": "9952",
"type": 1,
"items": [
{
"code": "AUD",
"value": 604.84
},
{
"code": "CAD",
"value": 586.36
},
{
"code": "CHF",
"value": 441.56
},
{
"code": "EUR",
"value": 389.87
},
{
"code": "GBP",
"value": 346.01
},
{
"code": "HKD",
"value": 345.31
},
{
"code": "JPY",
"value": 501.67
},
{
"code": "NZD",
"value": 642.29
},
{
"code": "USD",
"value": 441.50
}
]
}
I have to traverse the entire object and create a string with all the values for the property code. I have written a recursive function that solves the purpose, but that is using a global variable called codes. How can I change that method to use a local variable instead of global.
Here's my code:
getAllCodes(data) {
for (const key in data) {
if (data.hasOwnProperty(key)) {
if (Array.isArray(data[key])) {
this.getAllCodes(data[key]);
} else if (typeof data[key] === 'object') {
if (data[key]['code']) {
this.codes += `${data[key].code}+`;
} else {
this.getAllCodes(data[key]);
}
}
}
}
}
mapwould work. . It would help if you posted example data that reflects the actual problem.