0

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]);
          }
        }
      }
    }
  }
1
  • 1
    The data you posted is not really nested — a simple map would work. . It would help if you posted example data that reflects the actual problem. Commented Jan 15, 2019 at 17:13

2 Answers 2

1

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));

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.