How to recursively add unknown primitive elements?

baran

New Member
#1
I want to be able to recursively add elements to a single object, and can't use the salutations[element] syntax as the value of each key will be determined by user input, so I need to primitively use salutations to set each object of greetings.
Mã:
greetings = { key: value, chain: {} }
salutations = greetings.chain
for(var i = 0; i < j; i++){
    salutations = { key: value, chain: {} }
    salutations = salutations.chain
}
I want the result on the first iteration to be greetings.chain = { key: value, chain: {} }, and the second iteration to be greetings.chain.chain = { key: value, chain: {} }, and so forth.

Is this possible?
 

Admin

Administrator
Thành viên BQT
#2
Your code almost works. The parameters of the for loop are a little mixed up and you want to set the new chain before you reassign salutation in the loop:
Mã:
let greeting = { key: 'value', chain: {} }
let salutations = greeting
for(var i = 0; i<5; i++ ){
   salutations.chain = { key: 'value', chain: {} }
   salutations = salutations.chain
}

console.log(greeting)
console.log(greeting.chain.chain.chain.chain)
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top