I made a FIDDLE for you. I am storing a stack string and then output it, if the property is of primitive type:

function iterate(obj, stack) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property], stack + '.' + property);
                } else {
                    console.log(property + "   " + obj[property]);
                    $('#output').append($("<div/>").text(stack + '.' + property))
                }
            }
        }
    }

iterate(object, '')

Update: 17/01/2019

There used to be a different implementation, but it didn't work. See this answer for a prettier solution

Answer from Artyom Neustroev on Stack Overflow
🌐
Composingprograms
composingprograms.com › pages › 29-recursive-objects.html
2.9 Recursive Objects
The definitions of __len__ and __getitem__ are in fact recursive. The built-in Python function len invokes a method called __len__ when applied to a user-defined object argument. Likewise, the element selection operator invokes a method called __getitem__. Thus, bodies of these two methods will call themselves indirectly.
Top answer
1 of 16
122

I made a FIDDLE for you. I am storing a stack string and then output it, if the property is of primitive type:

function iterate(obj, stack) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                    iterate(obj[property], stack + '.' + property);
                } else {
                    console.log(property + "   " + obj[property]);
                    $('#output').append($("<div/>").text(stack + '.' + property))
                }
            }
        }
    }

iterate(object, '')

Update: 17/01/2019

There used to be a different implementation, but it didn't work. See this answer for a prettier solution

2 of 16
86

The solution from Artyom Neustroev does not work on complex objects, so here is a working solution based on his idea:

function propertiesToArray(obj) {
  const isObject = val =>
    val && typeof val === 'object' && !Array.isArray(val);

  const addDelimiter = (a, b) =>
    a ? `{b}` : b;

  const paths = (obj = {}, head = '') => {
    return Object.entries(obj)
      .reduce((product, [key, value]) => 
        {
          let fullPath = addDelimiter(head, key)
          return isObject(value) ?
            product.concat(paths(value, fullPath))
          : product.concat(fullPath)
        }, []);
  }

  return paths(obj);
}
  
const foo = {foo: {bar: {baz: undefined}, fub: 'goz', bag: {zar: {zaz: null}, raz: 3}}}
const result = propertiesToArray(foo)
console.log(result)

EDIT (2023/05/23):

4 different (complete) solutions with full descriptions are available on LeetCode: https://leetcode.com/problems/array-of-objects-to-matrix/editorial/?utm_campaign=PostD19&utm_medium=Post&utm_source=Post&gio_link_id=EoZk0Zy9

Discussions

java - Is recursion with objects possible? - Stack Overflow
I have a class called Program which hold a grid. It has two methods possi() which saves all possible ways you can enter the grid and saves ArrayList possi with all possible entry points and method ... More on stackoverflow.com
🌐 stackoverflow.com
Recursion of Objects
Tell us what’s happening: You can Ignore the code as I have solved it with the normal “for loop” method with nested “ifs” and passed the test. However, the exercise before this taught us recursion and I was curious to know how (if even possible) it would be applied here? More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
5
0
July 14, 2020
Efficient way to do recursion with objects in Java? - Stack Overflow
In dynamic programming using Java I frequently want to pass an array or object as a parameter in the recursive step. However, in order to have the original value be un-modified I would have to clon... More on stackoverflow.com
🌐 stackoverflow.com
February 3, 2018
Nested object recursion trouble - javascript - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I am trying to write a recursive function that will check each nested object for an even number and return a final sum of those numbers. More on stackoverflow.com
🌐 stackoverflow.com
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › advanced working with functions
Recursion and stack
Or it’s an object with N subdepartments – then we can make N recursive calls to get the sum for each of the subdeps and combine the results.
🌐
Uo-cis211
uo-cis211.github.io › chapters › 03_1_Recursion.html
Recursion in Object-Oriented Programs | CIS 211 @ University of Oregon
The basic logic of recursion is the same for object-oriented programs as for recursive functions that do not involve classes and objects. Just as before, we must identify one or more base cases and one or more recursive cases that build up complete results from simpler cases. The key difference is that with classes and objects, the recursive structure of the algorithms is often the same as the recursive structure of the objects.
🌐
DEV Community
dev.to › a_b_102931 › searching-through-a-nested-object-using-recursion-regular-expressions-and-sets-bm7
Searching Through a Nested Object Using Recursion, Regular Expressions, and Sets - DEV Community
March 11, 2020 - That means we need to use recursion to iterate through those values, and do so until we the value is a string. Here, we can use typeof to check if the value at each key is an object.
🌐
DEV Community
dev.to › eellin6 › manipulating-keys-in-an-object-using-recursion-2cb7
Manipulating Keys in an Object Using Recursion - DEV Community
November 18, 2020 - In the event that you may need to replace a key in an object, you can use a short little function that cleverly uses recursion to replace the key in an object.
Find elsewhere
🌐
Hillside
hillside.net › plop › plop98 › final_submissions › P21.pdf pdf
07/27/98 5:25 PM 1 Copyright  1998, Bobby Woolf. All rights reserved.
January 1, 1998 - Serialization algorithms, whether they produce text or binary output, usually use recursion. The · algorithm serializes an object by serializing the root and then recursively serializing its (persistent)
🌐
Medium
medium.com › swlh › how-to-use-recursion-to-flatten-a-javascript-object-17e43cc00159
How to Use Recursion to Flatten a JavaScript Object | by amkemp | The Startup | Medium
July 11, 2020 - A walkthrough of a recursive algorithm problem. Given an object oldObj, write a function flattenObject that returns a flattened version of it. If a certain key is empty, it should be excluded from the output.
🌐
OpenReplay
blog.openreplay.com › openreplay blog › explaining recursion in javascript
Explaining Recursion in JavaScript
October 13, 2022 - In the preceding code createDeepCopy() is a recursive function. It creates a deep copy of an object passed to it through its input argument.
🌐
Designcise
designcise.com › web › tutorial › how-to-do-recursion-in-javascript-object-literal-method
How to Do Recursion in JavaScript Object Literal Method? - Designcise
February 13, 2022 - You can create recursive functions in a JavaScript object literal in the following ways: Using a Named Function Expression; Using a Named Function Defined Outside the Object Literal Scope; Referring to the Object Method Using this.
🌐
Rice
clear.rice.edu › comp201 › 04-spring › lectures › recursion
Comp201: Principles of Object-Oriented Programming
The similarity between recursive algorithms and recursive data structures is because in an OO system, the structure drives the algorithm. That is, it is · the form of the data structure that determines the form if the algorithm. In an OO system, objects are asked to perform algorithms as they pertain to that object--that is, an algorithm on an object is a method of that object.
🌐
Boot.dev
blog.boot.dev › javascript › how to recursively traverse json objects
How to Recursively Traverse JSON Objects | Boot.dev
September 22, 2019 - In the code above, printArrayRecursive prints one element from the list, then calls itself again with the next index. Each successive call to itself prints the next element, and so on. The recursion continues until the base case is reached.
🌐
freeCodeCamp
forum.freecodecamp.org › curriculum help
Recursion of Objects - Curriculum Help - The freeCodeCamp Forum
July 14, 2020 - Tell us what’s happening: You can Ignore the code as I have solved it with the normal “for loop” method with nested “ifs” and passed the test. However, the exercise before this taught us recursion and I was curious to k…
Top answer
1 of 4
2

This exhibits a classic recursion antipattern: passing the result (sum) down the call stack as a parameter while also trying to pass it up as a result, leading to a confused state of affairs and double-counting.

Here's a fundamental rule of thumb for recursion: data dependencies (the things used to compute a result) are the parameters, results are return values.

Make sum local to the frame, then accumulate on it during the frame, either because each element is a number (leaf node in the tree search) or it's a child that should be explored recursively. Don't return immediately in the loop or you will miss some of the children.

function nestedEvenSum(obj) {
  let sum = 0;

  for (const k in obj) {
    if (obj[k].constructor === Object) {
      sum += nestedEvenSum(obj[k]);
    }
    else if (typeof obj[k] === "number" && obj[k] % 2 === 0) {
      sum += obj[k];
    }
  }

  return sum;
}

const obj = {
  a: 2,
  c: {
    c: {
      c: 2
    },
    cc: 'b',
    ccc: 5
  },
  e: {
    e: {
      e: 2
    },
    ee: 'car'
  }
};

console.log(nestedEvenSum(obj));

Note that this algorithm ignores arrays.

Also note that the function's design is highly rigid due to the % 2 === 0 predicate. You might consider using a function that traverses any nested structure and returns an array or generator of results that can then be filtered, or a function that allows an arbitrary callback predicate to perform the filtering.

One exception to the one-way data flow rule is that sometimes you'll want to accumulate results onto a parameter array as an optimization rather than returning and merging multiple arrays as you move back up the call stack, but that doesn't apply here.

2 of 4
1

I think I figured it out.

First, you're returning if you find an object, which means you'll stop early, so I removed the early 'return'.

Second, you're double-counting if you find an object, because you're passing in the sum you already have and then adding it to the sum you already have.

Check this out, just a couple small changes:

function nestedEvenSum(obj, sum = 0) {
  for(const k in obj) {
    if (obj[k].constructor === Object) {
      sum = nestedEvenSum(obj[k], sum);
    }
    if (typeof obj[k] === "number" && obj[k] % 2 === 0) {
      sum += obj[k];
    }
  }
  return sum;
}

const obj = {
  a: 2,
  c: {c: {c: 2}, cc: 'b', ccc: 5},
  e: {e: {e: 2}, ee: 'car'}
}

console.log(nestedEvenSum(obj));

🌐
Ashish Maurya's Blog
blog.theashishmaurya.me › flatting-an-object-and-array-using-recursion-and-other-methods
Flatting An object and Array Using Recursion and other Methods
September 27, 2022 - Hello Guys, How are you? I decided to write small snippets of code and hacks I find while developing things that might help you guys too. So Today I Will be showing a recursive way to flatten an array and object . This gonna be a short tutorial for y...
🌐
Princeton
cs.princeton.edu › courses › archive › spr00 › cs111 › labs › recursion › 2.html
Computer Science 111 -- Lab 9 -- Page 2
In computer programming, when we talk about recursion we are usually describing a section of code (such as an object method) which, as part of its operation, calls itself.
🌐
W3Schools
w3schools.com › java › java_recursion.asp
Java Recursion
Recursion in Java is a method that calls itself, breaking a problem into smaller steps.
🌐
DEV Community
dev.to › nitinreddy3 › recursion-to-update-deeply-nested-objects-f7e
Recursion to update deeply nested objects - DEV Community
July 5, 2020 - Here we are iterating over the list and checking whether the current value matches any of the child element's 'name' value and if it does then we update the object or we recursively go inside the array of objects.