0

I have a JSON file with data and I want to create a function that inserts to a list only the values of each object.

How can I write this code to run unlimited times and do the same, check if the value is not an object push it to list, or if it's an object he needs to do the same check.

Here is the code example, I just looking for a better way to write this, thanks!

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 = [];

Object.values(data).forEach(v => {
    if(typeof v !== 'object') return list.push(v);
    Object.values(v).forEach(v => {
        if(typeof v !== 'object') return list.push(v);
        Object.values(v).forEach(v => {
            if(typeof v !== 'object') return list.push(v);
            Object.values(v).forEach(v => {
                if(typeof v !== 'object') return list.push(v);
                Object.values(v).forEach(v => {
                    if(typeof v !== 'object') return list.push(v);
                    Object.values(v).forEach(v => {
                        if(typeof v !== 'object') return list.push(v);
                        Object.values(v).forEach(v => {
                            if(typeof v !== 'object') return list.push(v);
                        });
                    });
                });
            });
        });
    });
});

console.log(list)
Asaf
  • 949
  • 2
  • 13
  • 14

1 Answers1

1
  const list = [];

  const pushToList = (obj) => {
    const values = Object.values(obj);
    for (const value of values) {
      if (typeof value === 'object') {
        pushToList(value);
      } else {
        list.push(value);
      }
    }
  };

  pushToList(data);
  console.log(list);
ttquang1063750
  • 803
  • 6
  • 15