Retrieving an object from an array in Javascript

Here is the structure of my response body, which is stored in a variable. When I use console.log(body), this is what I see:

[
   {
      "key1":"value1",
      "key2":"value2",
      "key3":"value3"
   }
]

I am attempting to access "key3" with the following code:

console.log(body[0].key3) 

However, when I run this command, I receive undefined as the output. I am unsure what is causing this issue. If I simply type

console.log(body[0])

I get a string [.

Thank you for your assistance.

Answer №1

The Issue Explained

Your JavaScript code is focusing on a specific property within an object:

Let's illustrate what's happening with the following example:

const string = 'Hello';
console.log(string[0] === 'H'); // true
console.log('H'.key3 === undefined); // true


The Resolution

To resolve this, you should use JSON.parse on the string:

const body = `
[
   {
      "key1":"value1",
      "key2":"value2",
      "key3":"value3"
   }
]
`;

const parsed = JSON.parse(body);
console.log(parsed[0].key3);

Answer №2

body seems to be a string - you can convert it to an object using JSON.parse:

var body = '[{"key1": "value1","key2": "value2","key3": "value3"}]';
console.log(body[0]);
body = JSON.parse(body);
console.log(body[0].key3);

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

Toggle visibility of the last cell in a nested table by clicking on the first cell in each row of the table

I am looking to create a nested table structure for displaying data, as shown in the following link. Below is the code I have implemented in grid view in asp.net, but now I am attempting to implement it in HTML. The issue at hand: When clicking on the ...

Using a nodeJS proxy server to capture and manipulate http/https responses

I am working on developing a nodeJS proxy server that can modify the response from a server. My goal is to be able to access google.com without having to navigate to an address like http://localhost:8000/google. The proxy should operate in the background s ...

Issue with displaying content within a custom element for children was not seen

The content within the 'Child content' span is appearing in the Light DOM, but for some reason it's not being displayed on the actual page (refer to the screenshot provided). Does anyone have any insights as to why it might not be visible? ...

Determine the 'source' attribute value of the image (img) with a dynamically changing Id

Below is the code snippet: <img id="simple_captcha-ad089ff4819" src="/simple_captcha?code=a35401d"> The id of the above img tag changes constantly with each new action. For example, the next id could be "simple_captcha-sfw454sdfs". Therefore, I n ...

Utilizing Vue.js for Keyboard Binding

I'm brand new to coding and Vue, and I've hit a roadblock in my project. I'm creating a JavaScript calculator that needs to be usable both with a mouse and keyboard. While I've managed to make it work with the mouse, I just can't ...

What is the best way to turn off autocorrect in a textarea on IE11 without turning off spellcheck?

In my experience, disabling the spellcheck attribute seems to solve the auto-correct issue, but it also eliminates the underlining of misspelled words. <textarea id="TextArea1" spellcheck="false"></textarea> I prefer to keep spellcheck enabl ...

Upon publishing and globally installing the Node npm package, the error "use strict: command not found" was encountered

When attempting to publish my npm package, I encountered an issue. After installing the package globally and running the CLI command, the following errors occurred: /.nvm/versions/node/v0.12.2/bin/myPack: line 1: use strict: command not found /.nvm/versio ...

Leveraging the power of fullpage.js to activate Velocity.js/Blast.js animations

Referencing a solution shared on this forum: Velocity.js/Blast.js starting opacity at 0 I am currently working with Velocity.js and Blast.js to implement a basic word-by-word loading animation, commonly used. This setup also involves Cycle2. Additionally, ...

Exploring the possibilities of integrating JSONP with Framework7

I've been attempting to retrieve images from the Instagram public API using ajax and JSONP: var target = https://www.instagram.com/p/BP3Wu_EDXsjdT5Llz13jFv2UeS0Vw0OTxrztmo0/?__a=1?callback=?'; $$.ajax({ ty ...

JavaScript Slider Carousel for React framework

Can anyone assist with this? I need to rewrite everything in a standard algorithm, not as it is currently. I have three elements and I would like to create an infinite loop carousel where the next button takes me back to the first element when I reach the ...

Adding a class to individual elements generated through a v-for loop: a step-by-step guide

I have been working on a basic inventory "checker" that generates 14 divs labeled as either "active" or "inactive". Using Vue, I am able to create these divs with a simple v-for loop: <div class="inventory"> <div class="item" v-for="index in 14" ...

Remove a property name within angularjs that is specified in a json file

In the JSON file, there is a field name. The content of the JSON file is as follows: Data_underscore:1, Datawithoutunderscore:2, Data space:3 //error If I create a table in Angular using this JSON, how can I retrieve the value of the third one (D ...

What is the process for incorporating a custom attribute into an element with Vue directives?

One of the challenges I'm facing is dealing with a custom attribute called my-custom-attribute. This attribute contains the ID for the element that needs to have the attribute added or removed based on a boolean value. Although I've implemented ...

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

How can I use PHP to retrieve a specific JSON post by passing it as a parameter in the URL?

I'm facing a challenge with creating a RESTful API using PHP without any frameworks or databases. I've successfully parsed JSON data in PHP, but I'm struggling to access a specific post based on the query parameter entered in the URL. Here ...

Tips for populating a 2D array with random colors using Java

I'm currently working on a brick-breaker game and have been attempting to create a grid of randomly colored boxes. However, each time I run the code, the colors keep changing which is not what I want. I would like the colors to be set randomly once an ...

I am keen on implementing the bootstrap template within a react project, however, I am encountering difficulties in incorporating the

Exploring how to implement a bootstrap template in React has been quite an interesting journey. After successfully importing all the necessary CSS files into my component page, I encountered an issue while trying to utilize the JavaScript files. Although ...

Guide to automating the versioning of static assets (css, js, images) in a Java-based web application

To optimize the efficiency of browser cache usage for static files, I am seeking a way to always utilize cached content unless there has been a change in the file, in which case fetching the new content is necessary. My goal is to append an md5 hash of th ...

Maintain the selected image

I am working on a program that allows users to choose images and I have given them the pseudo-class. .my_image_class:hover{ border:3px solid blue; -webkit-box-sizing: border-box; } This makes the images bordered in blue when hovered over, giving a "sele ...

Convert an array of strings in C# into a JSON array using serialization

In my _Layout.cshtml file, I have the following code. The purpose is to populate some security items in my JavaScript code. LoggedIn and username work fine, but there seems to be an issue with how the roles are being displayed in the JavaScript. The Roles ...