1

I am making a function where i give the object path in a variable. I use this function after i got my data from the database.

function find(object, path, cb) {
  return cb(object[path]);
}

var object = {user:{firstname:"bob"}};
find(object, "user", function(data){});

This works fine with objects on the first level of the object but what if i want a object from the second level or higher:

"user.firstname"

When i try to run this through the find function wil it give a not defined error. How can i improve my function?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Ajeo
  • 73
  • 5
  • 11
  • Maybe that is just a simplified example, but I don't really see the point of the find function when you could just do `(function(data){})(object.user.firstname)`. – JJJ May 26 '15 at 08:32
  • Hmm maybe a good idea to just do that. I think that i was thinking to difficult :) – Ajeo May 26 '15 at 08:36

2 Answers2

1

You can do it manually by split function and iteratively executing this pattern:

var properties = path.split(".");
var value = obj;
for(prop of properties)
{
  value = value[prop];
}
suvroc
  • 3,058
  • 1
  • 15
  • 29
1

You could make your find function recursive. Besides making the path an array instead of a string gives you the option to do this for multiple layers.

function find (object, path, cb) {
    if (path.length > 1) return find(object[path.shift()], path, cb);
    return cb(object[path.pop()]);
}
var object = {user: {firstname:"bob"}};
find(object, ["user","firstname"], function (data){console.log(data)});
David Snabel
  • 9,801
  • 6
  • 21
  • 29