I have a JSON file containing data, and I am looking to create a function that extracts only the values from each object and adds them to a list.
Is there a more efficient way to write this code so it can run indefinitely and continue pushing non-object values to the list while recursively checking and handling objects?
Below is an example of the JSON data and the JavaScript code. Any suggestions for improving the code are greatly appreciated!
JSON Data
{
"el1": "Custom Text1",
"el2": "Custom Text2",
"el3": {
"el4": "Custom Text3",
"el5": {
"el6": "Custom Text4",
"el7": {
"el8": "Custom Text5",
"el9": {
"el10": {
"el11": {
"el12": "Custom Text6"
}
}
}
}
}
}
}
JS Code
const data = require('./data.json');
let list = [];
function extractValues(obj) {
Object.values(obj).forEach(v => {
if (typeof v !== 'object') {
list.push(v);
} else {
extractValues(v);
}
});
}
extractValues(data);
console.log(list);