0

I hope you are very well.

I am trying to find an complex object in an Object in Angular from a String (the content of this String is dynamic).

For example:

 let variable = {
      "name":"Rick",
      "family": {
        "son":"Andy"
      }
    };

When I try to read the name attribute, I can find it with the code:

console.log(variable["name"]);

When I try to read the family attribute, I can find it with the code:

console.log(variable["family"]);

However when I try to read the son attribute, I have tried to make with the code:

console.log(variable["family.son"]);

But I have gotten an undefined value, I found that I can use any of the followings codes:

console.log(variable["family"]["son"]);
console.log(variable["family"].son);

But it is not working for me, because I need to search the attribute from a String (the attributes are Dynamics), Does someone know how can I solve this.

The String contains the attribute path, for instance: "family.son" or "family"

Regards.

J. Abel
  • 890
  • 3
  • 17
  • 38
  • And this string contains what? This has nothing to do with Angular or AngularJS BTW. It's a pure JavaScript or TypeScript question. – JB Nizet Jan 24 '20 at 17:01
  • 1
    You're not using an array either. You're using an object – gabriel.hayes Jan 24 '20 at 17:04
  • So split the string using `.` as the separator, and use a loop to get the properties one by one. – JB Nizet Jan 24 '20 at 17:06
  • @nullptr.t there is not any wrong with use two String, however for my case I need to make it with once String, please help me reading the post. – J. Abel Jan 24 '20 at 17:08

1 Answers1

0

Try something like this:

const dotPathAccessor = (src, path) => {
    const parts = path.split('.');
    return parts.reduce((obj, prop) => obj[prop], src);
}
const variable = {
    "name": "Rick",
    "family": {
        "son": "Andy"
    }
};

console.log(dotPathAccessor(variable, "family.son"));

// you can use a Proxy object to make it simpler
// with this prototype, you can now get a dot proxy for any object using `object.getDotProxy`
// and access it using dot paths
Object.prototype.getDotProxy = () => new Proxy(variable, {
    get(obj, prop) {
        return dotPathAccessor(obj, prop);
    }
});
const dotProxy = variable.getDotProxy();

console.log(dotProxy["family.son"]);
gabriel.hayes
  • 2,267
  • 12
  • 15