A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error.

Here is the JSON Array(data) content:

[{"6011":
 [{"occupancy":"2","time":"2017-11-10 00:00:00"},
 {"occupancy":"1","time":"2017-11-10 00:30:00"},
 {"occupancy":"2","time":"2017-11-10 01:00:00"}]
}]

Code snippet for accessing the data:

var room = outerJSON.name;

var jsonObject = jQuery.parseJSON(JSON.stringify(data));

var innerArray = jsonObject[room]; // This line returns undefined
var innerArray2 = jsonObject.get(room); // The error "Uncaught TypeError: jsonObject.get is not a function" occurs here

Answer №1

Your items are stored within an array, so make sure to direct your code to the initial column of the array jsonObject by using [0] like this:

var innerArray = jsonObject[0][room];

var data = [{
  "6011": [{
      "occupancy": "2",
      "time": "2017-11-10 00:00:00"
    },
    {
      "occupancy": "1",
      "time": "2017-11-10 00:30:00"
    },
    {
      "occupancy": "2",
      "time": "2017-11-10 01:00:00"
    }
  ]
}];

var room = "6011";
var jsonObject = jQuery.parseJSON(JSON.stringify(data));
var innerArray = jsonObject[0][room];

console.log(innerArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

When the variable room is assigned the value of 6011 or "6011", and the array contains objects other than just {"6011":}, it becomes necessary to first locate that specific object within the array. This can be achieved by using the find method and accessing the room property through [room].

var jsonObject = [{ "6011": [{ "occupancy": "2", "time": "2017-11-10 00:00:00" }, { "occupancy": "1", "time": "2017-11-10 00:30:00" }, { "occupancy": "2", "time": "2017-11-10 01:00:00" } ] }, { "6012": [{ "occupancy": "2", "time": "2017-11-10 00:00:00" }, { "occupancy": "1", "time": "2017-11-10 00:30:00" }, { "occupancy": "2", "time": "2017-11-10 01:00:00" } ] }],
  room = 6011;

var foundObject = jsonObject.find(obj => obj.hasOwnProperty(room));

console.log(foundObject && foundObject[room]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Encountering a Parsing error while utilizing redux: Unexpected token present

Trying to implement Redux for managing the searchField state on the website. After creating action.js, reducer.js, constant.js, and redux.connect() function, An error occurred: Parsing error: Unexpected token 62 | return <div className=&apo ...

Setting up a Web application testing environment on its own

Embarking on my journey in web application development and testing, I am currently involved in a project that requires me to create a standalone environment for testing the web application. The main goal is to ensure the web application is easily testable ...

Dealing with Large JSON Strings in ASP.NET MVC Views

Large JSON Objects (approximately 1.5 MB) are received in Controller C1. They are then converted to strings and stored in a hidden label in View V1. The JSON data in V1 is utilized by parsing it in JavaScript J1. An occurrence of Out of Memory Excepti ...

What steps should I take to generate a stylized date input in javascript?

Looking to dynamically create a date string in JavaScript with the following format: dd-MMM-yyyy Need the dd part to change between 1 and 29 each time I generate the variable within a loop Month (MMM) should be set as Jan ...

Put a watch on a variable as soon as it is set

When initializing a variable, I want to use the $watch function in Angular without it automatically initializing right away. Is there a way to accomplish this? $watch $scope.$watch(function () { return $scope.character.level; }, function (ne ...

Quicker Solution to Iteration in Google Apps Script with JavaScript

I've set up a for loop to extract sales data from an array (salesLog) and transfer it to a designated sheet (targetSheet) in columns. The sales data is spread across multiple columns in the array. The loop adds up the columns between columnStart and c ...

In JavaScript, a "switch statement" retrieves a test value from a "input type text" by accessing the value using getElementByName.value

Attempting to test 7 possible values for the variable 'a' by passing it to a function from user input in seven 'input type text' boxes, then checking each value individually with clicks on 7 'input type image' elements. Howeve ...

Organize based on 2 factors, with emphasis on 1

Looking for a way to sort a list of posts by two variables - date (created) and score (score>). The main goal is to prioritize the sorting based on the score, so that the highest scoring posts appear first.</p> <p>To clarify, the desired so ...

Error Occurred: ngRepeat directive encountered an invalid expression while attempting to render the

HTML <tr ng-repeat="sale as examples"> <td class="text-right"> @{{sale.sales_person}}</td> <td class="text-right"> @{{sale.sales_total}}</td> <td class="text-right"> @{{sale.sales_target_amount}}</td> ...

Can the details of a package be retrieved from a Nuget private store using a REST API?

Currently working on an Angular 8 project that involves displaying the details of Nuget packages from a custom store. I am wondering if it is possible to retrieve package details from an NPM custom store using a REST API? Something similar to: https://lea ...

Inserting strings into a SQL database using values from JSON-encoded arrays can be achieved using the

Hello there! I am facing an issue with storing a string generated from JSON encode into MySQL. It seems that the array is not returning anything. Here's the code snippet in question: $com = array("1-1","1-2","1-3"); $classcom=array(); for ...

Find the sum of values in an array of objects if they are identical

[{ingName: "milk", quantity: "1.5", unit: "cups"}, {ingName: "sugar", quantity: "0.25", unit: "cups"}, {ingName: "vanilla extract", quantity: "1.0", unit: "tsp&quo ...

What causes the object to be updated with new values when I update reference variables in JavaScript?

Imagine having an object named x with values x = { a: 'abc', b: 'jkl' }, Next, I am assigning this object x to a new local variable y using var y = x. Now, when the value of var y changes as y.a = 'pqr', y.b = 'xyz&apos ...

Smoothly rotating an object in Three.js with a custom function

I successfully created a Rubik's Cube using Three.js, and everything is functioning as intended. However, I would like to add an animation when turning the cube instead of it snapping into place instantly. How can I achieve a smoother turning effect? ...

Adding a new row to a table is causing issues with jQuery

var info = [{ "pin": "015-08-0011-000-01", "arp": "015-08-0011-000-01", "tin": "342-432-423-000", "firstname": "John", "middlename": "James", "lastname": "Jones", "suffix": "", "qtr": "1st ...

Filtering JSON array data in Typescript can help streamline and optimize data

Recently diving into Angular, I am facing a challenge with filtering data from a JSON array. My goal is to display names of items whose id is less than 100. The code snippet below, however, is not producing the desired result. list : any; getOptionList(){ ...

Is there a way to determine if text can be parsed into a POJO without the need for error handling, Jackson?

Whenever I use ObjectMapper to convert a string to POJO, I find myself consistently enclosing my code in try-catch blocks to ignore any errors that may arise. ObjectMapper mapper = new ObjectMapper(); try { mapper.readValue(body, A.class); } catch (I ...

Searching through a mongoDB database

I have successfully created a register page that sends user inputs to a mongoDB atlas. Now, I am facing a challenge in implementing a login page where users can log in. I am struggling to locate the specific key-value pair needed to validate the login cred ...

Sending form data from a third-party website to Django

Currently, I am running a Django website that holds user information. My goal is to host forms on external websites, such as a newsletter signup form. I want to be able to extract data from a queryset in the URL and send it back to my Django site. At the m ...

Unable to invoke functions in the child window

In my Vue page, I have a script that opens a child window using the code snippet below: this.presentation = window.open( this.$router.resolve({name:'presentation'}).href, 'child window', 'width=auto,height=auto' ) ...