Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search recursively for value in object by property name

Tags:

I'm building an utility function that should search for a property name and return its value once it is found. It should do this recursively:

// Function util.findVal = (object, propName) => {   for (let key in object) {     if (key === propName) {       console.log(propName)       console.log(object[key])       return object[key]     } else {       util.findVal(object[key], propName)     }   } }  // Input object: {   photo: {     progress: 20   } }  // Usage util.findVal(object, 'progress') 

However the console log goes forever and the browser crashes. What am I doing wrong?

EDIT:

This is how I'm calling the function:

// Input  item: {   photo: {     file: {},     progress: 20   } }  this.findProgress(item)  methods: {   findProgress (item) {     return util.findVal(item, this.propName)   } } 
like image 400
alex Avatar asked Nov 15 '16 07:11

alex


1 Answers

You could use Object.keys and iterate with Array#some.

function findVal(object, key) {      var value;      Object.keys(object).some(function(k) {          if (k === key) {              value = object[k];              return true;          }          if (object[k] && typeof object[k] === 'object') {              value = findVal(object[k], key);              return value !== undefined;          }      });      return value;  }    var object =  { photo: { progress: 20 }};  console.log(findVal(object, 'progress'));
like image 180
Nina Scholz Avatar answered Sep 20 '22 07:09

Nina Scholz