0

I have a script which receives a JSON formatted file as input and allows the user to call out a JSON object name for specific processing. I loop through the JSON file using a foreach() to process the specific items requested by the end user.

In this example The JSON input file has an object array called "socks". The requested JSON object name could be input by the user as "socks" as this would be the object they would like to have the code perform a function on.

I push all of these "socks" to a new array to perform the work on.

//working code
jsonDataIn.socks.forEach(function(s) { 
            newArray.push({ socks:s })
        });

The above code functions as needed because I have hardcoded the array name as 'socks'. I cannot figure out how to assign the array name as a variable to apply the users input.

//I'd tried assigning just the array name as a variable, as well as both the data and array and those both are not valid.
let inputValueFromUser = 'socks';
let arrayNameVar=jsonDataIn.inputValueFromUser;
arrayNameVar.forEach(function(s) { 
            newArray.push({ [inputValueFromUser]:s })
        });

nor this

let inputValueFromUser = 'socks';
let arrayNameVar=inputValueFromUser;
jsonDataIn.arrayNameVar.forEach(function(s) { 
            newArray.push({ [inputValueFromUser]:s })
        });

In the above code the [inputValueFromUser] works for assigning the value to the newArray, but I cannot figure out how to get it to work inline as a form of 'jsonDataIn.inputValueFromUser.forEach()'. I found many examples if I were using multiple arrays in a forEach loop, but not how to pass the 'inputValueFromUser' as an array name. I know it has to be a simple solution that I'm missing. Any assistance is appreciated.

All of the failed code that I've tried to make work has resulted in "TypeError: Cannot read properties of undefined (reading 'forEach')"

BPaukst
  • 1
  • 1
  • I think you are asking about [nested objects/arrays in JSON](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json), and that already has an accepted answer (that's why I marked your question as "duplicate") – muka.gergely Jul 13 '22 at 22:17
  • 1
    Thank you, one of those solutions you listed had the answer. `jsonDataIn[inputValueFromUser].forEach(function(s) [ newArray.push({ [inputValueFromUser]:s }) });` was the answer. I needed to use object[arrayAsVariable] versus object.arrayAsVariable. – BPaukst Jul 13 '22 at 22:41

0 Answers0