Program-Me-Rev
Program-Me-Rev

Reputation: 6624

How read data from a JSON arry object in Javascript

I am trying to get a value from a JSON array in Javascript :

The JSON array looks like :

[
   {
      "_id": 0,
      "_entityMetadataList": [
         {
            "_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101696032.jpg",
         },
         {
            "_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101694488.jpg",
         }
      ],
      "_timeCreated": "Tue Jan 15 06:10:04 2019\n",
      "_timeUpdated": "Tue Jan 15 06:10:04 2019\n",
      "objectEntity": {
         "_id": 0,
         "_EntitySiteGUID": -1
      }
   }
]

How I go about it :

app.post('/sound', function (req, res) {
    let entitiesArray = req.body['filter'];

    console.log('entitiesArray: ' + JSON.stringify(entitiesArray._entityMetadataList[0]._metadataValue))

(this is in a Node environment, by the way)

I, however keep getting the error :

TypeError: Cannot read property '0' of undefined  

Upvotes: 0

Views: 61

Answers (3)

emilles
emilles

Reputation: 1179

Looks like you missed that the outermost reference is an array

revEntitiesArray[0]._revEntityMetadataList[0]._metadataValue

When in doubt, assign each part of your path expression to a local variable and step through with a debugger.

Upvotes: 0

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26644

Maybe this code can help

data = [
   {
      "_id": 0,
      "_revEntityMetadataList": [
         {
            "_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101696032.jpg",
         },
         {
            "_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101694488.jpg",
         }
      ],
      "_timeCreated": "Tue Jan 15 06:10:04 2019\n",
      "_timeUpdated": "Tue Jan 15 06:10:04 2019\n",
      "revObjectEntity": {
         "_id": 0,
         "_revEntitySiteGUID": -1
      }
   }
]`

data[0]["_revEntityMetadataList"][0]

Upvotes: 1

brk
brk

Reputation: 50291

Seems you also need to pass the index for revEntitiesArray.

Try this

console.log('revEntitiesArray: ' + 
JSON.stringify(revEntitiesArray[0]._revEntityMetadataList[0]._metadataValue))

Upvotes: 4

Related Questions