在 Javascript 中动态调用几个级别的对象


var myObj = {
    bar_foo : "test",
    bar : {
       foo : "hi there";
         },
    foo : {
          bar : {
                 foo: "and here we go!"
                 }
           }
     }

如何获得这个:

var arr = [["bar", "foo"], ["foo", "bar", "foo"]];

要返回此内容:

myObj["bar"]["foo"];
myObj["foo"]["bar"]["foo"];

arr可以是任意长度,以便它遍历对象。

所以我们知道我们可以像这样动态调用对象的值:

var 通常 = myObj["bar_foo"];

其中normally等于"test"

但是这种技术假设我们知道遍历的深度。

我试图做的是通过提供一个数组来检索对象值

["bar", "foo"]

这基本上与

myObj["bar"]["foo"];

我这样做

的原因是因为我正在根据我想要从 arr 获得的值创建一个新对象。

所以最终结果将是:

arr_new = myObj.someMethod(arr);

arr_new在哪里:

arr_new : ["hi there", "and here we go!"];

我希望这能澄清这一点。

如果您使用的是下划线(或者可以使用本机 JS mapreduce ),请尝试以下操作:

var myObj = {
  bar: {
    foo: "hi there"
  },
  foo: {
    bar: {
      foo: "and here we go!"
    }
  }
};
var arr = [
  ["bar", "foo"],
  ["foo", "bar", "foo"]
];
function deepProp(arr, obj) {
  return _.reduce(arr, function(memo, val) {
    return memo[val];
  }, obj);
}
var deepProps = _.map(arr, function(deepArray) {
  return deepProp(deepArray, myObj);
});
console.log(deepProps); // => ["hi there", "and here we go!"]

可能有一个更优雅的解决方案;这是一个快速的黑客。似乎几乎可以做你想做的事!:P

Object.prototype.someMethod = function (arr) {
  function a (obj, array){
    var res = obj[array.splice(0, 1)[0]];
    if (typeof res === 'object' && array.length) {
      return a(res, array);
    }else{
      return res;
    }
  }
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    result.push(a(this, arr[i]));
  }
  return result;
};

JSBin>> 演示

也许这就是你要找的?

function getObjValue( arr, obj){
    var tmp=obj;
    for(i=0;i<arr.length;i++){
        tmp=tmp[arr[i]];
    }
    return tmp
}
alert( getObjValue( arr[1],myObj)); // "and here we go!"

要创建值数组,请执行以下操作:

var result=arr.map(function(subArr){
   return  getObjValue(subArr,myObj);
})

演示

我在不使用库的情况下做了一个小提琴,展示了一个可能的答案:

http://jsfiddle.net/EfrainReyes/6s9HY/2/

var traverseObject = function(obj, arr) {
    var results = [];
    for (var i = 0; i < arr.length; i++) {
        var tempObj = obj;
        for (var j = 0; j < arr[i].length; j++) {
            tempObj = tempObj[arr[i][j]];
        }
        results.push(tempObj);
    }
    return results;
};

当然,这假设参数始终有效,但可以添加验证检查。

最新更新