簡體   English   中英

javascript從字符串數組構造對象

[英]javascript construct an object from an array of strings

我有以下數組

var testArray = ["test1", "test2", "test3"];

以及其中包含其他對象的obj

var obj.test1.test2.test3 = "test";

我想foreach的testArray

並獲得以下內容

obj[testArray[0]][testArray[1]][testArray[2]]

obj["test1"]["test2"]["test3"]

等於obj.test1.test2.test3並返回“ test”

如您所言,我們可以利用obj["test1"]表示法將自己更深地嵌套到目標對象中。 在這種情況下,在每次迭代中,我們都將所指向的“頂部”重新分配為最后一次迭代的子級。

var obj = { test1: { test2: {test3: 'test' }}};
var current = obj;

var arr = ['test1', 'test2', 'test3'];
for(var i = 0; i < arr.length; i++){
    if(current === undefined){ break; }
    current = current[arr[i]];
}

console.log(current);

這個怎么樣:

var testArray = ["test1", "test2", "test3"];
var value = [obj].concat(testArray).reduce(function(prev, curr) {
     return prev[curr];
});

但是請記住,IE <= 8( Reduce reference )不支持reduce

function extractDeep(obj, propPathArr) {
   var prop = obj;
   propPathArr.forEach(function (item) {
      prop = prop[item];
   });
   return prop;
}

像這樣打電話

alert(extractDeep({a: {b: {c: "The property!"}}}, ['a', 'b', 'c']));

注意:

  • 您確實應該添加一些錯誤檢查。
  • forEach不適用於所有瀏覽器

jsFiddle可以在這里找到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM