Help with object in js access properties

1

I usually access the properties of the objects like this:

nombre = body.first_name;

The problem is that the route I receive it by parameter.

var ruta="first_name"

and when putting

nombre= body.ruta;

tries to access the path property and not the first_name property

    
asked by Alexis Granja 11.07.2017 в 15:00
source

4 answers

3

To access a property, it is enough to access through the brackets [ ] , the operator must be a text

For example

var obj = {first_name: "Jhon Doe"}
var ruta="first_name"
nombre = obj[ruta] 
console.log(nombre)

The line obj[ruta] expands to obj["first_name"] which is equivalent to doing obj.first_name therefore returns Jhon doe

    
answered by 11.07.2017 / 15:14
source
3

The other solutions will most likely fail when you try to access a nested object , that is, a more complex object that has another object inside, and we want to access a pripiedad that is well inside, well, I did a small utilitarian function that can help solve this problem:

function getProps(obj, path) {
  var arr = path.split('.');
  var parent = obj;
  var name = arr[0];

  arr.slice(1).forEach((fieldName) => {
    parent[name] = parent[name] || {};
    parent = parent[name];
    name = fieldName;
  });
  return parent[name];
}


var obj = {
  bar: {
    foo: 3,
    hello: {
      there: {
        foo: 3
      }
    }
  }
}

console.log(getProps(obj, 'bar.foo'));
console.log(getProps(obj, 'bar.hello.there'));

Update

I leave the complete example of how I use it, which suits it for the answer, it is more complete because you can also modify the json, and create the parent fields as necessary:

export function resolvePath(obj: any, path: string) {
    const arr = path.split(".");
    let parent = obj;
    let name = arr[0];

    arr.slice(1).forEach((fieldName) => {
        parent[name] = parent[name] || {};
        parent = parent[name];
        name = fieldName;
    });

    return {
        get(): any {
            return parent[name];
        },
        set(value: any) {
            parent[name] = value;
        },
        delete() {
            delete parent[name];
        },
        ref() {
            return [parent, name];
        },
    };
}
    
answered by 11.07.2017 в 16:11
2

You can also use lodash.get link . From the example of this link:

var object = { 'a': [{ 'b': { 'c': 3 } }] };
 
console.log(_.get(object, 'a[0].b.c'));
// => 3
 
console.log(_.get(object, ['a', '0', 'b', 'c']));
// => 3
 
console.log(_.get(object, 'a.b.c', 'default'));
// => 'default'
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
    
answered by 25.07.2017 в 18:37
1

Suppose your Body object is like this

function Body(){

 this.first_name = "Alexis";


}

You can access that property first_name directly

function Body() {

  this.first_name = "Alexis";


}

var body = new Body();

console.log(body.first_name);

Or you can also pass the string that contains the property you want.

body["first_name"] 

If you know that the route is going to arrive from the user.extended.propiedad format, you can do split(".") and stay the last element

function Body() {

  this.first_name = "Alexis";


}

var body = new Body();


var ruta =  "user.extended.first_name";

var propiedad = ruta.split(".")[2];

console.log(body[propiedad]);
    
answered by 11.07.2017 в 15:15