Reputation: 4319
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]);
}
}
}
}
}
Upvotes: 0
Views: 74
Reputation: 386634
You could take a function which recursively collects the code
property from a nested object.
const
getCode = object => [
...['code' in object ? object.code : ''],
...Object.values(object).filter(o => o && typeof o === 'object').map(getCode)
].join(' ');
var object = { code: 'a', nodes: { code: 'b', nodes: { code: 'c', nodes: { code: 'd' } } } };
console.log(getCode(object));
Upvotes: 1
Reputation: 37755
I don't see need of recursion
here. you can do it using reduce simply
let obj = {"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}]}
let codeString = obj.items.reduce((output,{code})=>{
output += code + ' '
return output;
},'')
console.log(codeString)
Upvotes: 1