0

I just want to add objects inside objects dynamically using array technique. I know how do we add Objects - those are Object[key] or Object.key but suppose I thing I have to add multiple objects dymanically using function

Note: below example is just for demonstration

let array = ['first','second','third']
let object = {}

function addObject(key) {
  object[key] = "someValue"
}

for (var i = 0; i < array.length; i++) {
  addObject(array[i])
}

This gives output like this { first: 'someValue', second: 'someValue', third: 'someValue'}. Actually I want my output something like nested object {first:{second:{third:'somevalue'}}} not exactly this but a nested object first > second > third.

My Actual question is like how to add objects inside object in this situation. What is the correct syntax for this. Like object[first][second][third] is standard way to achieve but I can't add + operator in the left side or calling array(['first.second.third']) `

function addObject(key) {
  object[key] + [key] = "someValue"
}

or calling

array(['first.second.third'])

1 Answer 1

2

I'd use reduceRight to iterate over the array starting from the end. Pass in the final property value as the initial accumulator, so you get { third: 'someValue' } on the first iteration, and return it so it's the new accumulator. On subsequent iterations, do the same thing - create another object enclosing the last returned accumulator.

const array = ['first','second','third']
const nestedValue = 'someValue';
const result = array.reduceRight(
  (a, prop) => ({ [prop]: a }),
  nestedValue
);
console.log(result);

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this , I didn't get this well, I have to look it , Is there any way to pass array(['first.second.third']) directly so it get everytime. there are also four five six ... and this should be added dynamically.
It's possible, but a bit more convoluted... extract the first (only) item from the array and then split by periods. theArr[0].split('.') then pass to .reduceRight.
I really have to look this first, thanks for your valuable answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.