Valary o
Valary o

Reputation: 577

Why my recursive function works only for one level?

I am trying to learn how to cope with the objects and arrays and I saw many ways of iterating objects but recursing doesn't work for me and I don't understand why. What am I doing wrong?

I need to loop through an object and just slightly change something in an array. In my case, it's uppercasing the keys

Here is what I've got for now


const development = {
  port: 8080,
  db: {
    username: "jkdfs",
    password: "dsfsdg",
    name: "kslfjskd",
    test: { test: 12, another: 'value' }
  },
  token_secret: "jfkjdsj",
  hash_rounds: "kjsfkljdfkl"
};

function throughObject(obj) {
  let collection = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      let value = obj[key];

      if (typeof obj[key] !== 'object') {
        collection[key.toUpperCase()] = value;
      } else {
        collection[key.toUpperCase()] = nestedObject(obj[key]);
      }
    }

    function nestedObject(nested) {
      const sub = {};

      for (const k in nested) {
        let v = nested[k];

        if (typeof nested[k] !== 'object') {
          sub[k.toUpperCase()] = v;
        } else {
          nestedObject(v);
        }
      }
      return sub;
    }
  }
  return collection;
}

const r = throughObject(development);
console.log(r);



Upvotes: 0

Views: 322

Answers (1)

adiga
adiga

Reputation: 35222

When you're recursively calling the function on an object value, you still need to assign it to the sub object: sub[k.toUpperCase()] = nestedObject(v). Also, you don't need 2 different functions.

const development = {
  port: 8080,
  db: {
    username: "jkdfs",
    password: "dsfsdg",
    name: "kslfjskd",
    test: { test: 12, another: 'value' }
  },
  token_secret: "jfkjdsj",
  hash_rounds: "kjsfkljdfkl"
};

function nestedObject(nested) {
  const sub = {};

  for (const k in nested) {
    const v = nested[k];
    
    if (typeof nested[k] !== 'object')
      sub[k.toUpperCase()] = v;
    else
      sub[k.toUpperCase()] = nestedObject(v); // <- HERE
  }
  return sub;
}

console.log(nestedObject(development))

Here's a shorter version using Object.fromEntries()

const development={port:8080,db:{username:"jkdfs",password:"dsfsdg",name:"kslfjskd",test:{test:12,another:"value"}},token_secret:"jfkjdsj",hash_rounds:"kjsfkljdfkl"};

const convert = o =>
  Object.fromEntries(
    Object.entries(o).map(([k, v]) => 
      [k.toUpperCase(), Object(v) === v ? convert(v) : v]
    )
 )

console.log(convert(development))

Upvotes: 3

Related Questions