Javascript: How to get property of an object using an Array string?

How to get a property of an object using the string array (property name)? (the last element in the array is an internal property of the object)

See the code below:

Convenient way:

let myObject = {
    "property": {
        "subproperty": {
            "targetproperty": "Hi, We done it!"
        }
    }
};
let myString = "property:subproperty:targetproperty";
let parts = myString.split( ":" );
console.log( myObject[ parts[ 0 ] ][ parts[ 1 ] ][ parts[ 2 ] ] ); // Output: "Hi, We done it!"

Evalay:

let myObject = {
    "property": {
        "subproperty": {
            "targetproperty": "Hi, We done it!"
        }
    }
};
let myString = "property:subproperty:targetproperty";
let parts = myString.split( ":" );
let code = "myObject";
for ( let i = 0; i < parts.length; i++ ) {
    code += "['" + parts[ i ] + "']";
}
code += ";";
console.log( code );
console.log( eval( code ) ); // Output: "Hi, We done it!"

Eval is evil. so i need a cleaner way to do this.

How can I do this without useful and useful work?

+4
source share
7 answers

You can use .reduce():

let myObject = {
  "property": {
    "subproperty": {
      "targetproperty": "Hi, We done it!"
    }
  }
};
let myString = "property:subproperty:targetproperty";
let value = myString.split(":").reduce(function(obj, prop) {
  return obj && obj[prop];
}, myObject);

console.log(value);
Run codeHide result
+9
source

For the loop:

function getByValue(arr, value) {

  for (var i=0, iLen=arr.length; i<iLen; i++) {

    if (arr[i].b == value) return arr[i];
  }
}

.filter

function getByValue2(arr, value) {

  var result  = arr.filter(function(o){return o.b == value;} );

  return result? result[0] : null; // or undefined

}

.forEach

function getByValue3(arr, value) {

  var result = [];

  arr.forEach(function(o){if (o.b == value) result.push(o);} );

  return result? result[0] : null; // or undefined

}

, , .. 6, ..., . .

function getByValue4(arr, value) {
  var o;

  for (var i=0, iLen=arr.length; i<iLen; i++) {
    o = arr[i];

    for (var p in o) {
      if (o.hasOwnProperty(p) && o[p] == value) {
        return o;
      }
    }
  }
}
+3

;)

, , .

, , , /, , .

,

0

parts, .

function valueFromPath(obj, path) {
  for (var i = 0; i < path.length; ++i) {
    obj = obj[path[i]];
  }

  return obj;
};

valueFromPath(myObject, parts);

, , - .


Alternatively, you can use traverse . In particular traverse # getpath .

traverse(myObject).get(parts);
0
source

Here is a recursive approach, it will return undefinedif the property is not found:

const getPath = (o, keyPath, delimiter = '.') => {
    if (Array.isArray(keyPath)) {
        keyPath = keyPath.join(delimiter)
    }
  // o might not be an object when called recursively
  if(Object(o) === o) {
    let keys = keyPath.split(delimiter);
    let key  = keys.shift();

    if(o.hasOwnProperty(key)) {
      if(keys.length) {
        // there are more keys to check, call with attribute and remaining keys
        return getPath(o[key], keys.join(delimiter), delimiter);
      } else {
        // no more keys to check and object does have property
        return o[key];
      }
    }
    // didn't early return from having the key above, object does not have property
    return undefined;
  } else if(keyPath.length === 0) { 
    // o is not an object, but there is no remaining keyPath, so we will assume we've unwound the stack
    return o;
  }
  // not an object and keyLength is non-zero, object does not contain property
  return undefined;
};

let myObject = {
    "property": {
        "subproperty": {
            "targetproperty": "Hi, We done it!"
        }
    }
};

console.log(getPath(myObject, "property:subproperty:targetproperty", ":"));
Run codeHide result
0
source

You can use the solution reduce:

var obj = {prop1: {prop2: {prop3: 'xpto'}}};
var props = ['prop1','prop2','prop3'];

var result = props.reduce((acc,val)=>acc[val],obj);
console.log(result);
0
source

You can do the following:

function getNestedValue(o,...a){
  var val = o;
  for (var prop of a) val = typeof val === "object" &&
                                   val !== null     &&
                                   val[prop] !== void 0 ? val[prop]
                                                        : undefined;
  return val;
}

let myObject = {
    "property": {
        "subproperty": {
            "targetproperty": "Hi, We done it!"
        }
    }
};
let myString = "property:subproperty:targetproperty";

console.log(getNestedValue(myObject, ...myString.split(":")));
Run codeHide result
0
source

Source: https://habr.com/ru/post/1672589/


All Articles