Exploring a javascript array using a for loop with a specified range

In my MVC app, the controller serializes a list of objects using JavaScriptSerializer() to create a JSON object that is then passed to the client side view.

Oddly enough, when attempting to iterate through the object using a ranged for loop, each object appears as undefined. However, using a regular for loop and indexing the object with the current iteration value in square brackets allows me to access each sub-object successfully (for example, this works:

for(var i = 0; i < jsonObj.length; i++)
compared to this: for(var sub in jsonObj)). Why does the ranged for loop fail in this scenario?

JSON Object:

[
    "Obj1": {
            "Value1": "3454234",
            "Value2": "345643564",
            "Value3": "665445",
            "Value4": "True"
        },
        "Obj2": {
            "Value1": "3454234",
            "Value2": "345643564",
            "Value3": "665445",
            "Value4": "True"
        },
        "Obj3": {
            "Value1": "3454234",
            "Value2": "345643564",
            "Value3": "665445",
            "Value4": "True"
        }
]

EDIT

for(var sub in finalJson){
  console.log(sub["Value1"])
}

Answer №1

The JSON Object you have submitted is not in the correct format. It appears to be an array of key-value pairs instead of a properly structured JSON object enclosed in curly braces { ... } rather than square brackets [ ... ]. You can verify the variable type using jsonObj instanceof Array;. If it evaluates to true, then that may be the cause of the issue.

Answer №2

Your JSON is invalid; you should remove the object names to make it a valid list:

[
   {
      "Value1": "3454234",
      "Value2": "345643564",
      "Value3": "665445",
      "Value4": "True"
   },
   {
      "Value1": "3454234",
      "Value2": "345643564",
      "Value3": "665445",
      "Value4": "True"
   },
   {
      "Value1": "3454234",
      "Value2": "345643564",
      "Value3": "665445",
      "Value4": "True"
   }
]

You can then use a ranged loop like this:

JsonObj.forEach(function(obj) {
   console.log(obj);
})

Alternatively, you can convert it to an object with nested objects as properties:


{
  "Obj1": {
    "Value1": "3454234",
    "Value2": "345643564",
    "Value3": "665445",
    "Value4": "True"
  },
  "Obj2": {
    "Value1": "3454234",
    "Value2": "345643564",
    "Value3": "665445",
    "Value4": "True"
  },
  "Obj3": {
    "Value1": "3454234",
    "Value2": "345643564",
    "Value3": "665445",
    "Value4": "True"
  }
}

Then, you can loop through using the keys like this:

for(var key in JsonObj) {
   console.log(key);
}

The reason your second loop wasn't working is because for..in is meant for iterating through an object's keys, but your JSON is an array of objects.

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

Determine the total value of NodeJS for a particular date by parsing through JSON data

Currently in the process of learning NodeJS and exploring data calculations, Suppose we have JSON data from a URL with around 100 entries: [{ "ID": "01", "sales": 11, "points": 5, "date": & ...

Combining multiple arrays of arrays in JavaScript

I am dealing with an array that contains nested arrays. This particular array is called template https://i.sstatic.net/QIs0Q.png template consists of 2 arrays, but the number can vary and there can be multiple levels of arrays within each one. Here' ...

The scroll feature is not functioning properly in detecting the CSS function for the final div

$(document).ready(function() { $(document).on("scroll", onScroll); //smoothscroll $('a[href^="#"]').on('click', function(e) { e.preventDefault(); $(document).off("scroll"); $('a').each(func ...

Issues with using a personalized font in a Stenciljs project

Looking for guidance on implementing a custom font in my Stenciljs app. I have the otf file, unsure if an npm package is necessary. Here's my code: filestructure: -src --components --assets ---Anurti-Regular.tiff ---Anurti-Regular.ttf friends-l ...

What methods are available to incorporate arithmetic when defining a style attribute?

Is there a way to achieve arithmetic operations in CSS, like calculating margin-left: -60px + 50% of the width of the parent div? I'm eager to find a solution, whether it involves JavaScript or any other method. Any help would be greatly appreciated. ...

Need help maintaining selected div in navbar as active even after page refresh?

I've been struggling to maintain the selected tab as active on page reload. I have tried various solutions found here but none seem to work for me. Currently, the active class is applied correctly when clicked, but upon navigating to a new page, it re ...

I am having trouble modifying the value of a struct in the WinForms Property Grid

It's puzzling why this issue is occurring, but I am determined to make adjustments to the XNA color value: private Color _color = Color.White; [System.ComponentModel.Category("VisibleInEditor")] [System.ComponentModel.TypeConverter(typeof(System.Com ...

What steps should I take to ensure my button functions correctly after I have finished writing?

I am attempting to create blog buttons that will input text into a textarea when clicked. However, I am experiencing an issue where the text won't be added if I have already been typing or editing in the textarea before clicking the button. <butto ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

What is the best way to utilize App.config for storing and accessing URLs when running Selenium tests in C#?

Instead of hardcoding URLs into my unit tests, I decided to create an App.config file where I can store them. This way, if the URL changes, I only need to update it in one place. Here is a snippet from my App.config (URLs altered for privacy): <configur ...

jquery expanding the width of the final element

Is there a way to increase the width of the last 'th' in a string? I want it to be the current width plus 20px. Here is the code on Fiddle var header="<th id='tblHeader_1' style='width: 80px;'><span>Id</span&g ...

Navigate back to the previous page while retaining all original information

When my custom error handling is triggered in the controller, I struggle to maintain the original data while redirecting back to the same page. Let's say I have a webpage called Create.cshtml. On this Create page, there are form controls that require ...

Substitute empty spaces and organize the text layout

I'm struggling to figure out how to substitute the whiteSpace in an aggregate request using MongoDB and also how to remove a specific part of a string (most likely requiring regex). Here's an example of my document: { "_id": "57dfa5c9xxd76b ...

Issues with BinaryWriter and MemoryStream interoperation in C#

I am currently dealing with a class that includes the following method: public System.IO.Stream ToBinary () { int length = 4144; System.IO.Stream stream = null; System.IO.BinaryWriter writer = null; stream = new System.IO.MemoryStream(len ...

Ways to extract the value without considering the key

In my database, there is a JSON array that I want to extract only the value from and send it to an ajax call. Here is an example of the JSON string stored: { "cells": [ { "type": "devs.TooledModel", "position": ...

Avoid serializing fields with default values in Pydantic/JSON conversion

I am working on a class that includes a member with a default value. However, I do not want this default value to be included in the serialization process. For instance: import json from typing import List from pydantic import BaseModel from pydantic.jso ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...

Retrieval of components from JSON array of objects

I have a JSON array containing objects stored on the server. How can I access the first object to print its contents? The data is in the following format: [ { "eventId": "8577", "datasetId": "34", "nodeId": "8076", "typeId": "4", "type": ...

Using AJAX to send a request to a PHP file that populates a popover, but the functionality only works

I have created a basic search bar where with every .keyup() event, an asynchronous request is sent to a PHP file which then populates the data in a Bootstrap popover. The issue I am facing is that the popover displays the data only once. After entering th ...

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 ...