[英]Setting the value of a multidimensional object or array property in Javascript
是的,我知道如何在Javascript 中遍歷數組(類型)。 事實是,我想知道如何通過一組給定的indexes
設置multiDimensionalArray
數組的值,以使其盡可能通用。 例如,我有一個長度為 3 的數組(也可以是長度為 4、100、...):
var indexes = [0, "title", "value"];
我知道可以通過像這樣放置索引來設置多維數組(mArray):
multiDimensionalArray[0]["title"]["value"] = "Jeroen";
或multiDimensionalArray[indexes[0]][indexes[1]][indexes[2]] = "Jeroen";
給定的索引數組可能會有所不同並且並不總是包含相同的索引名稱,因此我正在尋找這樣的解決方案:
multiDimensionalArray[indexes] = "Jeroen";
如果這樣,我不知道如何對分配進行編碼。 我在 Google/Stack Overflow 上搜索過。 也許我使用了錯誤的關鍵字。 誰能幫我?
謝謝!
由於喬納斯的例子,下面的例子是我如何使它工作:
var json = [{ "hello": { "world": 1, "world2": 2 }, "bye": { "world": 1, "world2": 2 } }]; var indexes = [0, "hello", "world2"]; var value = "value"; indexes.slice(0,-1).reduce((obj, index) => obj[index], json)[indexes.pop()] = value; console.log(json);
所以想象一下你有一個這樣的結構:
var array=[[["before"]]];
那你要
var indexes=[0,0,0];
var value="value";
實際做:
array[0][0][0]="value";
這可以通過reduce輕松實現:
indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
解釋:
indexes.slice(0,-1) //take all except the last keys and
.reduce((obj,index)=>obj[index] //reduce them to the resulting inner object e.g. [0,0] => ["before"]
,array) //start the reduction with our main array
[indexes.pop()]=value;// set the reduced array key to the value
var array=[[[0]]]; var indexes=[0,0,0]; var value="value"; indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value; console.log(array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.