A method of iteration that allows us to traverse through an object, regardless of whether it contains a single item or an array of items, is known as dynamic looping

I am dealing with a JSON output that can have different types of data:

  1. There may be an array of objects like this:

    var data = {
                "EARNINGS": [
                       {
                         "PAYMENT": "1923.08",
                         "REPORTING_NAME": "Regular Salary",
                         "CATEGORY_NAME": "Standard Earnings"
                       },
                       {
                         "PAYMENT": "0",
                         "REPORTING_NAME" "Spot Bonus",
                         "CATEGORY_NAME": "Supplemental Earnings"
                       }
                     ]
    }
    
  2. Or just a single object like this:

      var data = {
           "EARNINGS": 
                   {
                     "PAYMENT": "1923.08",
                     "REPORTING_NAME": "Regular Salary",
                     "RUN": "1923.08",
                    }
               };
    

I'm struggling with how to loop through the "EARNINGS" object. It's straightforward when it's an array of objects, but when it's a single object, I need to determine whether it's an array or not.

Answer №1

To verify, you can use the following code snippet: Array.isArray(data); this function will return either true or false.

var data_single = {
  "EARNINGS": {
    "PAYMENT": "1923.08",
    "REPORTING_NAME": "Regular Salary",
    "CATEGORY_NAME": "Standard Earnings",
  }
};

var data_arr = {
  "EARNINGS": [
  {
    "PAYMENT": "1923.08",
    "REPORTING_NAME": "Regular Salary",
    "RUN": "1923.08",
  },
  {
    "PAYMENT": "0",
    "REPORTING_NAME": "Spot Bonus",
    "CATEGORY_NAME": "Supplemental Earnings"
  }
  ]
};

console.log(Array.isArray(data_single['EARNINGS']));
console.log(Array.isArray(data_arr['EARNINGS']));

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

Issue: Incompatibility in metadata versions detected for module .../ngx-masonry/ngx-masonry.d.ts. Level 4 version identified, whereas level 3 version

When using ngx-masonry, I encountered the following error message- ERROR in Error: Metadata version mismatch for module .../ngx-masonry/ngx-masonry.d.ts, found version 4, expected 3 Specifications: Angular 4 ngx-masonry 1.1.4 ...

Toggle the visibility of multiple divs by clicking on other divs

I have implemented a script on my webpage to toggle the visibility of certain divs by clicking on anchor tags. I found a solution that seems perfect for my needs, but unfortunately it is not working when I try to integrate it into my own website. I suspec ...

The Flutter error message states that a 'String' type is incompatible with an 'int' type when trying to access an 'index'

Seeking assistance for an app I am developing to fetch data from a URL post in JSON format. The data includes information about a person, such as their client details and address. However, when attempting to use this address information to send it to anoth ...

When using Laravel with jQuery Ajax, the search for the file address is unsuccessful

Learning Laravel has been a challenging journey for me. I've encountered numerous problems that have made it feel like more of a hindrance than a helpful tool. But the real story lies elsewhere. Working with Laravel 4 and jQuery 2, I attempted to fet ...

Retrieve the jsonb value from a json structure that includes a json array in PostgreSQL

I am working with a JSON column that contains data like the following: {"image_pose_array": [{"image_name": "0026568143_WS.jpg", "image_pose": "EXTRA", "is_blurred": false, "is_dark": fal ...

Acquire the Information from a Textarea That Has Been Edited by the User

My challenge lies in taking user-entered text from a content editable textarea and sending it via POST request, but the fields edited by the user are returning with an empty textContent. The code snippet below shows that each .entryRow (obj) contains multi ...

The error message "Babel - Unable to access property 'TYPED_ARRAY_SUPPORT' of an unspecified object" is being displayed

Encountering a recurring error when using the oidc-client library in my React project. The error message reads: Babel - Cannot read property 'TYPED_ARRAY_SUPPORT' of undefined Despite knowing about the Redux implementation of this library, I ...

Place an overlay element in the top-left corner of a perfectly centered image

Currently, there is an image that is centered on the screen using flexbox: .center-flex { display: flex; justify-content: center; } <div class="center-flex"> <img id="revealImage"> </div> An attempt is be ...

Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the fiel ...

Leveraging Discord.js to retrieve all messages sent while the bot was inactive

My plan is to create a bot that will store all messages sent in a channel into a txt file on my computer. However, the challenge is that since my computer is not always on when the bot is running, there are gaps in the stored messages in the .txt file. I a ...

Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and droppin ...

Limit the number of elements in an Angular object by using the filter function

I've implemented an angularjs filter method on a repeated array of items in an attempt to filter numbers using a limitTo filter. However, the result is not reflecting in the DOM. Below is the html code snippet: <div ng-controller="demo as d"> ...

Issues with my POST function across different domains

I have developed a MVC rest Web API with a method structured like this: public HttpResponseMessage PostBook(DtoBooks Book) { if (Book == null) { return Request.CreateResponse(HttpStatusCode.BadRequest); ...

Using Nextjs Image as the Background for Layout

I have a question regarding implementing a common background image for all pages in my app. Currently, I have the main page.js code that displays an image as the background using Next Image component. However, I would like this background to be present thr ...

Next-Auth: Access Session in _app.js Directly Without Using getServerSideProps

When working with React.js and React-Auth, it's important to note that calling server-side functions such as getServerSideProps can prevent you from exporting your project using next export. Below is the content of my pages/_app.js, which I structured ...

Verifying updates in the watchlist once data has been initialized upon mounting

When trying to edit a component, the data is loaded with mounted in the following way: mounted () { var sectionKey = this.$store.getters.getCurrentEditionKey this.table = _.clone(this.$store.getters.getDocumentAttributes[sectionKey]) this.ta ...

What could be causing Ember/handlebars.js to prepend 'app/' to my template file names?

Whenever I try to load my Rails ember app, I encounter a frustrating issue where Ember is unable to locate the application and index templates. Ember.TEMPLATES['application] and Ember.TEMPLATES['index'] Oddly enough, when I check Ember.TEM ...

Executing cross browser testing in Node JS consecutively within a single session: A step-by-step guide

When conducting cross-browser testing, I prefer to run the tests individually rather than all together in one session. This way, I can ensure that all test results are accurately logged and generated into a single HTML report at the end of each session. I ...

Manipulating JSON Elements using JavaScript in HTML

My objective is to alternate the visibility between the "prev" and "ext" elements retrieved from the JSON File in the following manner: Here is the link to JS Fiddle The menu bar appears as follows: [ "prev_Person1" "Person1" "ext_Person1" ... "Person2" ...

Why am I unable to retrieve data using jQuery and PHP?

I'm working with a PHP form that involves checkboxes: <form action="" method="post" id="CheckBoxForm"> foreach ( $results as $result ) : <input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).&a ...