"Using the check function in JavaScript to determine if a value

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);

Answer №1

  let array = [];

  const addToArray = (object) => {
    const properties = Object.values(object);
    for (const property of properties) {
      if (typeof property === 'object') {
        addToArray(property);
      } else {
        array.push(property);
      }
    }
  };

  addToArray(data);
  console.log(array);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conceal the HTML input element until the JavaScript has finished loading

Currently, I am using a JQuery plugin to style a form input with type 'file'. The plugin adds a new span over the input element to create a mask effect and encloses everything in a div. However, there is an issue where the standard HTML input box ...

When the initial image URL returns a 404 error, the ng-src path does not automatically switch to the alternative

I'm currently working on a webpage where I want to show an image only if the URL of that image is valid, using AngularJS. The challenge I'm facing is that ngIf only checks whether a value is null or not. So, even if the URL returns a 404 error, ...

How can you refresh the information shown in a separate component from the search input with a live search bar?

Currently, I am working on integrating a live search functionality into my Next.js application. While I have successfully managed to capture input changes, I am facing difficulties in filtering the results based on the user input. Here is a snippet of the ...

Struggling to grasp the syntax, trying to invoke a JavaScript function using an input button

I'm really struggling to grasp the xhtml syntax involved in calling a function with an input button. Despite my efforts to find a clear explanation, this concept still eludes me. Within the snippet of code from my book that I've been referencing ...

Does Highchart offer support for drilling down into sub-categories?

I want to implement a sub-sub drill down feature in my Chart using the following code snippet. // Create the chart Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Highcharts m ...

Utilizing AJAX to send a parameter to PHP for processing

I am facing an issue with a script that is supposed to send data to a PHP file when a user clicks on an element, but unfortunately, it's not functioning correctly. Below is the jQuery code: jQuery( document ).ready(function( $ ) { $('.rve_b ...

Having trouble with the @keyup event not functioning properly in Vue?

I'm attempting to trigger a method when the enter key is pressed, but for some reason it's not working. Here's the code snippet: <template> <div> <button @click="callEvent" @keyup.enter="callEvent"> Click </button ...

Is Material-UI suitable for a large-scale enterprise application?

We are in the process of transforming a massive and outdated MVC Java EE application into React. This particular application consists of a browser-based user interface with an extensive range of views that include intricate forms, listings, and links. It i ...

how to implement dynamic water fill effects using SVG in an Angular application

Take a look at the code snippet here HTML TypeScript data = [ { name: 'server1', humidity: '50.9' }, { name: 'server2', humidity: '52.9', }, { name: 'server3', humidity: ...

Function executed many times during click action

I have developed a web application that allows users to input any keyword or statement and receive twenty results from Wikipedia using the Wikipedia API. The AJAX functionality is working perfectly. The app should dynamically create a DIV to display each r ...

Organize an array of children with dependencies in PHP

I need to organize an array based on the values of its children. The array should first display parent-child pairs, followed by their respective children and grandchildren, all sorted according to the "Parent" value. Here's an example of such an array ...

The best method for quickly loading a webpage that is over 20MB in size

My website is a single-page calendar featuring a full year's worth of images. With 344 requests and a total load size of 20MB, the page consists of a simple PHP script without a database. The requests include a CSS file (15KB), 4 JS files (20KB), two ...

Showcasing unique characters from a json file onto a textview in an android

I am facing an issue with displaying special characters such as ñ from a JSON file stored in my assets folder. Even though I am trying to load and display the text using TextView, it does not show up correctly as ñ. Below is the code snippet I have bee ...

Decomposing the Retrofit response.body()

I am having difficulties with implementing Retrofit and understanding how to interpret the response body. I believe that there might be an issue with mapping my JSON data to POJO because the output is not what I expected when I print it out in the log. He ...

Updating the URL in React and Redux

I am currently working on developing an application using React and Redux (DVA) with Ant.Design as the main framework. I am facing an issue where I need to change the URL when a user clicks on a button, and connect that URL change to a specific action so t ...

Finding unique data stored in separate JSON files and loading them individually may require using different methods for

I have two JSON files named marker.json and marker.json0 that contain different latitude and longitude coordinates. To load them, I need to rename .json0 to .json (and vice versa), so that the new data from marker.json0 now resides in marker.json. This way ...

Setting up a JSON API through a console interface that connects to a relational database

I have been on the hunt for a tool or utility that offers a console-like feature for creating JSON data APIs using relational databases. While exploring options, I stumbled upon deployd () and emergent one (), but I am curious if there are similar tools a ...

React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse. this.state = { action: [], } <div> {this.state.action.map((value, index) => { return ( <div key={index} onMouseEnte ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

Correctly executed $.Ajax and $.Post requests consistently yield errors when sent from C#

I'm struggling to create a cross-domain web API method in C# that will return valid jsonp to Javascript. Despite returning valid JSON data, I keep encountering failure messages when trying to debug with F12 dev tools or Firebug. Here is my current co ...