2

I have an object like in below stackblitz and I want to check if key is Date or not. And then I'm adding 3 days to that date. I'm doing for this for not recursive object perfectly. But, when object is recursive, I couldn't do this. How can I achieve this? Performance is important for me because in my real life scenario my objects are very big and complex.

Stackblitz

  myObject = {
    aProperty: {
      aSetting1: 1,
      aSetting2: new Date(),
      aSetting3: 3,
      aSetting4: 4,
      aSetting5: 5
    },
    bProperty: {
      bSetting1: {
        bPropertySubSetting: new Date()
      },
      bSetting2: "bString"
    },
    cProperty: {
      cSetting: new Date()
    },
    dProperty: new Date()
  }


  convertButtonClick() {
    this.convert(this.myObject);
    console.log(this.myObject);
  }

  convert(obj) {
    for (var property in obj) {
      if (obj.hasOwnProperty(property)) {
        if (obj[property] instanceof Date) {
          obj[property].setDate(obj[property].getDate() + 3);
        }
      }
    }
  }
4
  • You have to traverse whole object, For that you need to use recursion. Or use BFS, DFS traversal Commented Mar 12, 2019 at 14:43
  • I tried recursion but, I didn't achieve @Amit Commented Mar 12, 2019 at 14:49
  • If your lucky based on some domain knowledge you could speed up the process. e.g as from depth/level 3 there wouldn't be any more dates down. or for e.g there are never more than x dates in 1 level. Commented Mar 12, 2019 at 14:54
  • 2
    Thanks @jcuypers and Amit. ConnorsFan 's answer is what I was looking for. Commented Mar 12, 2019 at 14:58

1 Answer 1

3

You can call convert recursively when you find that one of the properties is an object:

convert(obj) {
  for (let property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (obj[property] instanceof Date) {
        obj[property].setDate(obj[property].getDate() + 3);
      } else if (obj[property] instanceof Object) {
        this.convert(obj[property]);  // Recursive call
      }
    }
  }
}

See this stackblitz for a demo.

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

1 Comment

Thanks a lot @ConnorsFan. This is what I was looking for.

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.