簡體   English   中英

使用循環創建動態嵌套對象

[英]Create Dynamically Nested Objects with loops

我想動態創建一個嵌套的 object。 我可以創建硬編碼。 是否可以用循環來做到這一點?

result = {}
keys = ["a", "b", "c", "d"]

result[keys[0]] = {}
result[keys[0]][keys[1]] = {}
result[keys[0]][keys[1]][keys[2]] = {}
result[keys[0]][keys[1]][keys[2]][keys[3]] = "cool"

我想傳遞一個 integer,例如如果它是“3”,這應該創建一個 object,例如:

result = {
  "a": {
     "b": {
        "c": "cool"
     }
   }
}

如果是 4,:

result = {
  "a": {
     "b": {
        "c": {
           "d": "cool"
        }
     }
   }
}

很快...

編輯:

我還在檢查結果 object,以創建此嵌套結構。 如果還沒有任何字段,我只需創建 object。

使用此結構對數據進行分組。 有機會動態檢查這些嗎?

if (!result[keys[0]]) 
if (!result[keys[0]][keys[1]]) 
if (!result[keys[0]][keys[1]][keys[2]]) 

您可以reduceRight()使用reduceRight() 它只是從內部在鍵列表的最后一項開始,然后以“ cool”開始進行解決:

 let keys = ["a", "b", "c", "d"] let limit = 3 let result = keys.reduceRight((obj, key) => ({[key]: obj}), "cool") console.log(result) 

要限制對象停止的位置,您可以遍歷鍵的一部分。 例如:

 let keys = ["a", "b", "c", "d"] let start = 0 let stop = 3 // slices are don't inlcude the last item, so this will stop at index 2 let result = keys.slice(start, stop).reduceRight((obj, key) => ({ [key]: obj }), "cool") console.log(result) 

簡單的for循環解決方案。

 let result = {} let keys = ["a", "b", "c", "d"] let depth=3; let current = result for(let i=0;i<depth;++i){ let key = keys[i] if(i == depth-1) current[key] = 'cool' else current = current[key] = {} } console.log(result) 

如果要向給定對象添加新屬性,則可以使用該對象減少鍵,並為未給定鍵使用默認對象。 最后分配值。

 function setValue(object, path, value, limit) { var keys = path.slice(0, limit), last = keys.pop(); keys.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value; return object; } var result = { foo: 42 }, keys = ["a", "b", "c", "d"]; setValue(result, keys, 'cool'); console.log(result); setValue(result, keys, 'cool', 3); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

我會使用減速器以及一些基本測試來幫助我: https : //youtu.be/D6zLI8zrfVs

在此處輸入圖片說明

https://gist.github.com/brianswisher/2ce1ffe3ec08634f78aacd1b7baa31f9

使用 reduce 簡短而簡單

let object1= {}
keys = ['a', 'b', 'c']

keys.reduce((prev,curr,i)=>{
    prev[curr] = {}
    return prev[curr]
}, object1)

log(object1) 
// {
//   a:{
//     b:{
//        c:{}
//     }
//   }
// }

暫無
暫無

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

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