Receiving JSON data and saving it into an array in JavaScript

I have a JSON input that contains information about different categories including companies, countries, and persons.

{
    "Categories": {
        "Facets": [{
            "count": 1,
            "entity": "Company",
            "Company": [{

                "entity": "Ford Motor Co",

                "Ford_Motor_Co": [{
                    "count": 1,
                    "entity": "Ford"
                }]
            }]
        }, {
            "count": 4,
            "entity": "Country",
            "Country": [{

                "entity": "Germany",
                "Germany": [{
                    "count": 1,
                    "entity": "Germany"
                }],
                "currency": "Euro (EUR)"
            }, {

                "entity": "Italy",
                "Italy": [{
                    "count": 1,
                    "entity": "Italy"
                }],
                "currency": "Euro (EUR)"
            }, {

                "entity": "Japan",
                "Japan": [{
                    "count": 1,
                    "entity": "Japan"
                }],
                "currency": "Yen (JPY)"
            }, {

                "entity": "South Korea",
                "South_Korea": [{
                    "count": 1,
                    "entity": "South Korea"
                }],
                "currency": "Won (KRW)"
            }]
        }, {
            "count": 5,
            "entity": "Persons",
            "Persons": [{
                "count": 2,
                "entity": "Dodge"
            }, {
                "count": 1,
                "entity": "Dodge Avenger"
            }, {
                "count": 1,
                "entity": "Major League"
            }, {
                "count": 1,
                "entity": "Sterling Heights"
            }]
        }]

    }
}

I am trying to extract the values of the entity at each level in the JSON structure and store them in an array.

[Company, Ford Motor Co, Ford, ....... , Sterling Heights]

Currently, I can access the entities at the first level using the following code:

for (var k in h.Categories.Facets)
{

alert(h.Categories.Facets[k].entity);

}

However, I need help in navigating through the inner levels to retrieve all entity values. How can I achieve this?

Answer №1

To iterate through each entity, consider using a foreach loop. If the number of levels is known, nesting loops can be implemented. Otherwise, opt for a recursive function to handle the entities more efficiently.

Additional Information

Here is an example of a recursive function:

function retrieveEntities(entity)
{
   alert(entity);
   for (var level in entity)
   {
      retrieveEntities(entity[level].entity);
   }
}

Then utilize the function like this:

for (var key in data.Categories.Facets)
{
   retrieveEntities(data.Categories.Facets[key]);
}

Best of luck with your implementation!

Answer №2

This is a versatile recursive function:

function findEntities(input) {
    var entities = [];
    if ('entity' in input​) {
        entities.push(input.entity);
    }
    for (var property in input) {
        if (input[property] instanceof Object && input.hasOwnProperty(property)) {
            entities.append(findEntities(input[property]));
        }
    }
    return entities;
}
console.log(findEntities(someInput));

The following line:

 if (input[property] instanceof Object && input.hasOwnProperty(property)) { 

Prevents errors with numbers and null values, while input.hasOwnProperty(property) accommodates frameworks that modify the Object prototype.

Answer №3

An effective approach involves creating a recursive function that takes an array as input and extracts the elements from it.

Answer №4

To efficiently handle nested combinations, one effective approach is to implement a recursive function that iterates through all possible combinations:

const allEntities = [];
function extractNestedEntities(obj) {
   if (obj !== null) {
       const entityName = obj["entity"];
       console.log(entityName);
       if (entityName !== null) {
           allEntities.push(entityName);
           const adjName = entityName.replace(/ /gi, "_");
           const entities = obj[adjName];
           if (entities !== null) {
               for (let e in entities) {
                   const innerEntities = extractNestedEntities(entities[e]);
                   for (let inner in innerEntities) {
                       allEntities.push(innerEntities[inner]);
                   }
               }
           }
       }
   }
}    

for (let k in h.Categories.Facets) {
    console.log(h.Categories.Facets[k].entity);
    extractNestedEntities(h.Categories.Facets[k]);
}
console.log(allEntities.length);

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

Having trouble accessing undefined properties in ReactJs? Specifically, encountering issues when trying to read the property "name"?

I am facing an issue with using the data in my console even though I can log it. The structure of my data object is as follows: {_id: '616bf82d16a2951e53f10da4', name: 'abd', email: '[email protected]', phone: '123456789 ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...

How do the JavaScript thread and the Silverlight UI thread interact with each other?

While JavaScript operates on a single thread, Silverlight does not follow the same restrictions. However, when it comes to the interaction between JavaScript and Silverlight, it is crucial that communication occurs on the Silverlight UI thread. The relati ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

Can you explain the process of extracting images from JSON data using AJAX and jQuery?

Hello, I'm looking for guidance on incorporating jquery with AJAX to fetch images from a JSON file and showcase them on my website. Below is the code snippet I have put together. function bookSearch(){ var search = document.getElementById('sea ...

Check if a given string conforms to the JSONATA expression format

Here's the scenario: A user inputs a JSONATA expression into a form field. The form should show an error message if the entered JSONATA expression is invalid. Is there a regular expression or pattern that can determine the validity of a string as a ...

Enable checkboxes to be pre-selected upon page loading automatically

Although I've found a lot of code snippets for a "select all" option, what I really need is more direct. I want the WpForms checkboxes to be pre-checked by default when the page loads, instead of requiring users to press a button. My goal is to have a ...

Experience the convenience of Visual Studio Code's auto-completion feature for HTML tags even when working within an

My HTML file has a babel script embedded within it. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>React tutorial</title> <script src="https://unpkg.com/react@16/umd/react.development.js" ...

Sofa database - URL location

In my database, I have a "List" containing various products such as: { "_id": "car1", "_rev": "1-6e192e3f87447ec187052941cf365071", "price": "950", "shop": "Shop1" } To keep track of what products/cars I have at each of the 3 shops, I create ...

Showcase -solely one property object- from numerous property objects enclosed within an array

Hello, I am seeking assistance as I have recently begun learning about angularJS. I am working with objects that have keys such as: scope.eventList=[]; for(){ var event = { id : hash, ...

Enhanced approach to building with React and Express

Quick Summary: How can I set up a project using React on the front-end and Express on the back-end with just one package.json and node_modules folder? When starting a project that combines a React front-end and an Express back-end, my desired structure is ...

What is the best way to fulfill promises sequentially?

I'm currently facing a challenge with organizing promises in the correct order. I am developing a chat bot for DiscordApp using Node.js and have extensively searched both on this platform and Google. Despite trying Promise.all and an Async function, I ...

Is it possible for me to input a variable into the logical process of if(isset($_FILES['whatever']))?

I have recently started learning PHP and I'm in the process of creating a dynamic page that will update based on which form buttons are clicked. The functionality is working correctly, but my goal is to enable users to upload multiple files - either P ...

Tips for dynamically resetting the dataTable

When I create a datatable and add rows dynamically based on the selected option, I encounter an issue where I need to reinitialize the dataTable every time the option is changed. To address this, I have placed the reinitialization code inside the $("#selec ...

Converting images to greyscale or transparency within a ReactJS component

I am exploring ways to transform an image into grayscale or make it transparent before using it as a background in ReactJS. Is there a way to achieve this in ReactJS? My current code snippet is shown below: <GridListTile> <img style={{ -we ...

Navigating through a 3D world with just the tilt of

I am currently developing an immersive VR web application using three.js. I have integrated the device orientation controls from the Google Cardboard three.js demo for camera navigation. Now, I am looking to incorporate keyboard controls for additional fu ...

Create a regular expression that matches a combination of alphabets and spaces, but does not allow for

Can anyone provide a regular expression that allows for a combination of alphabets and spaces, but not only spaces? After searching extensively and reading numerous articles, I came across the expression /^[a-zA-Z\s]*$/, which unfortunately permits j ...

How can you tap into local storage in CSS while utilizing a chrome extension?

Can I access local storage from a Chrome extension's options file using CSS? Is it possible to use JavaScript to define a variable that can be utilized in CSS, or is local storage only accessible through JavaScript? If local storage is restricted to J ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...