1

I have an object with nested properties:

{ 
    a: { 
        b: { 
            c: { min: 1, max: 2  }, 
            d: 1 
        }
    }
 }

The nesting can be any amount of levels deep. It ends in either an object with one of the properties (min, max, in) or as a non object (string, number, bool)

I would like to generate a string for the path to those endpoints.

E.g. for above object I would like the following result:

objPaths(a)

=> {
     "a.b.c": { min: 1, max: 2 }
     "a.b.d": 1 
   }
1
  • It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the tour and How to Ask Commented Apr 25, 2018 at 15:12

2 Answers 2

1

You could create recursive function for this using for...in loop. Also if the value of the current property is an object you need to check if some of the keys is min or max before going to next level.

const obj = {"a":{"b":{"c":{"min":1,"max":2},"d":1}}}

const objPaths = (obj, paths = {}, prev = '') => {
  for (let key in obj) {
    let str = (prev ? prev + '.' : '') + key;
    if (typeof obj[key] != 'object') paths[str] = obj[key];
    else if (Object.keys(obj[key]).some(k => ['min', 'max'].includes(k))) paths[str] = obj[key];
    else objPaths(obj[key], paths, str)
  }
  return paths
}

const result = objPaths(obj);
console.log(result)

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

Comments

0

You could take an iterative and recusive approach and check if the object contains min or max keys, then take the object or value otherwise itrate the object.

function getPath(object) {
    function iter(o, p) {
        if (o && typeof o === 'object' && !['min', 'max'].some(k => k in o)) {
            Object.entries(o).forEach(([k, v]) => iter(v, p + (p && '.') + k));
            return;
        }
        result[p] = o;
    }

    var result = {};
    iter(object, '');
    return result;
}

console.log(getPath({ a: { b: { c: { min: 1, max: 2 }, d: 1 } } }));

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.