Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to Get Object property using Array of string? [duplicate]

How do i get object property using array of string (name of properties)? (the last element in array is the inner property of object)

See the code below:

Handy 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!"

Eval way:

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 it.

How do i do it without eval and handy job?

like image 404
Empire Avatar asked Dec 15 '22 00:12

Empire


2 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);
like image 182
JLRishe Avatar answered May 21 '23 17:05

JLRishe


For 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

}

If, on the other hand you really did mean for..in and want to find an object with any property with a value of 6, then you must use for..in unless you pass the names to check. e.g.

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;
      }
    }
  }
}
like image 38
Mrchipz Avatar answered May 21 '23 18:05

Mrchipz