Z
Z
zwezew2018-12-20 13:29:09
JavaScript
zwezew, 2018-12-20 13:29:09

How to get primitive properties of nested objects recursively?

link

How to make a return here to return the found values?

function getProp(o) {
   for(var prop in o) {
      if(typeof(o[prop]) === 'object') {
         getProp(o[prop]);         
      } else {
         //return o[prop];
         console.log(o[prop]);
      }
   }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-12-20
@zwezew

const getPrimitiveProps = (obj) =>
  Object.entries(obj).reduce((acc, [ k, v ]) => ({
    ...acc,
    ...(v instanceof Object ? getPrimitiveProps(v) : { [k]: v }),
  }), {});

or
const getPrimitiveProps = (obj) =>
  Object.assign({}, ...Object.entries(obj).map(([ k, v ]) =>
    v instanceof Object ? getPrimitiveProps(v) : { [k]: v }
  ));

V
VoidVolker, 2018-12-20
@VoidVolker

function getProp(o) {
    var result = [];
    for(var prop in o) {
        if(typeof(o[prop]) === 'object') {
            result = result.concat(getProp(o[prop]));
        }
    }
    return result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question