简体   繁体   中英

Access object inside an array - Javascript

This is how my response body looks like. Its stored in a variable and when i use console.log(body) I get the following.

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

Im trying to access "key3" using the following

console.log(body[0].key3) 

I get undefined. Im not sure what is wrong here. If i just do

console.log(body[0])

im getting a string [

Thanks for your help here.

body sounds like it's a string - JSON.parse it to an object:

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

The Problem Explained

Your JS is looking at the property on a specific character:

Take a look at the following example that will help demonstrate what is going on:

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


The Solution

You need to JSON.parse the string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM