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

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-recursively-map-object-in-javascript
How to Recursively Map Object in JavaScript ? - GeeksforGeeks
July 23, 2025 - Recursively mapping objects in JavaScript involves traversing through nested objects and applying a function to each key-value pair.
Discussions

javascript - JS Recursive object assign - Stack Overflow
I learned that when using Object.assign() it extends only the top level object. How can I deeply extend the object? For example, let's say I have the following source object: const source = { id... More on stackoverflow.com
🌐 stackoverflow.com
recursion - Recurse over a object - Javascript - Stack Overflow
Suppose I have the following object: var my_obj = { x: 0, y: [Object] } every time I call the function recurse_object I will add another element to my_obj, and create a recursive object: More on stackoverflow.com
🌐 stackoverflow.com
recursion - javascript object recursive function - Stack Overflow
Please note that using recursion in javascript can be dangerous as javascript doesn't have tail-call optimization and you can run to stack overflow easily if you're not carefull. ... This idea will fail if Q makes references to other properties of the object. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Generated recursive object based on array - Stack Overflow
Recursive solution will fail if array will contain too many elements. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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.
🌐
GitHub
gist.github.com › sphvn › dcdf9d683458f879f593
Recursively traverse object javascript, recurse json js, loop and get key/value pair for JSON · GitHub
April 3, 2019 - export function traverse(o: any, fn: (obj: any, prop: string, value: any) => void) { for (const i in o) { fn.apply(this, [o, i, o[i]]); if (o[i] !== null && typeof(o[i]) === 'object') { traverse(o[i], fn); } } }
🌐
CheatCode
cheatcode.co › tutorials › how-to-recursively-traverse-an-object-with-javascript
How to Recursively Traverse an Object with JavaScript | CheatCode
October 1, 2021 - How to write a function that looks for a specific key/value pair on an object and call that function recursively to traverse objects of an arbitrary depth.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › recursively-list-nested-object-keys-javascript
Recursively list nested object keys JavaScript
August 19, 2020 - const people = { Ram: { fullName: 'Ram Kumar', details: { age: 31, isEmployed: true } }, Sourav: { fullName: 'Sourav Singh', details: { age: 22, isEmployed: false } }, Jay: { fullName: 'Jay Grewal', details: { age: 26, isEmployed: true } } } const recursiveSearch = (obj, searchKey, results = []) => { const r = results; Object.keys(obj).forEach(key => { const value = obj[key]; if(key === searchKey && typeof value !== 'object'){ r.push(value); }else if(typeof value === 'object'){ recursiveSearch(value, searchKey, r); } }); return r; }; console.log(recursiveSearch(people, 'age'));
🌐
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.
🌐
GoLinuxCloud
golinuxcloud.com › home › javascript › how to recursively map object in javascript [solved]
How to recursively map object in JavaScript [SOLVED] | GoLinuxCloud
January 17, 2023 - If we wanted to create a new object ... map function in JavaScript, we can use a function that takes two arguments: the object to map and the transformation function to apply to each property....
🌐
Medium
medium.com › @ronald-roe › traversing-javascript-objects-by-recursion-8229f7da7915
Traversing JavaScript Objects by Recursion | by Ron Roe | Medium
March 8, 2023 - Used internally to determine where in the pathArray we are * * @returns {any|null} Requested config setting(s) */ const recurseObjectPath = (pathArray, inputObj, level = 0) => { // For each level of the array, get the next path let output; const currPath = pathArray[level]; // Push this object into the output output = inputObj[currPath]; // Prefix increment here will store the new value for us, then // pass it to the index to check, thus checking the next one if (typeof pathArray[++level] !== 'undefined') { // The path goes deeper, recurse into the next index output = recurseObjectPath(pathArray, inputObj[currPath], level); } return output ??
🌐
Medium
medium.com › @alaneicker › how-to-process-json-data-with-recursion-dc530dd3db09
Using Recursion in JavaScript to Traverse Nested Data Structures | by Alan Eicker | Medium
March 28, 2023 - Inside the loopThroughJSONfunction, we need to check if the current value is an object or an array. If it is an object, we will call the loopThroughJSON function recursively.
🌐
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 - The tricky thing with nested objects is that some values--but not all--are objects themselves. 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.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript tutorial › javascript recursive function
JavaScript Recursive Function
August 8, 2016 - However, as mentioned in the Function type tutorial, the function’s name is a reference to the actual function object. If the function name is set to null somewhere in the code, the recursive function will stop working.
🌐
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 - The final else, if the first two conditions aren't met, will set the new object's key/value equal to the original object's key/value. This will allow the rest of the object's keys that do not match the "newKey" to stay the same after the recursive calls.
🌐
Boot.dev
blog.boot.dev › javascript › how to recursively traverse json objects
How to Recursively Traverse JSON Objects | Boot.dev
September 22, 2019 - Even if a compiler supports loops, some problems are easier to solve with a recursive function. A good example is tree traversal. I often write recursive functions to find every property of any JSON object, or to search every file in a folder that may have an infinite number of nested subfolders.
Top answer
1 of 3
2

You could use a destructuring assignment for the wanted keys and use Array#map for getting a new array with only the one property and use Object.assign for the children objects by checking the children and if exist, take the urls from the children with a recursive call of the function.

function getUrls(array) {
    return array.map(({ url, children }) =>
        Object.assign({ url }, children && { children: getUrls(children) }));
}

var settings = [{ path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default' }, { path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default' }] }] }],
    urls = getUrls(settings);

console.log(urls);
.as-console-wrapper { max-height: 100% !important; top: 0; }

2 of 3
1

const settings = [
    {path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default'},
    {path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children:[
        {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children:[
              {path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default'}  

        ]}  
    ]}
];


function childrenUrls(childrens){
	return childrens.reduce(function(arr, obj){
		var newObj = {url: obj.url};
		if(obj.children) newObj.children = childrenUrls(obj.children);
		return arr.push(newObj), arr;
	}, []);
}


const newArray = childrenUrls(settings);

console.log(newArray);