Arjun Ram
Arjun Ram

Reputation: 369

Unable to read nested JSON object in Node.JS

I have a JSON node called 'data' that has an id. I want to store the value of that id but I'm unable to do so with my current syntax and I'm getting an error saying it's undefined.

How should I change my code to make this work?

My code snippet:

const transfer_ID = data.items.id;
    console.log("This is the transfer tree obtained", data);

data:

{ entity: 'collection',
  count: 1,
  items: 
   [ { id: 'trf_Ary1cWasdfGmHAc',
       entity: 'transfer',
       source: 'pay_ASrxasdfetwhAFv',
       amount: 390000,
       currency: 'INR',
       amount_reversed: 0,
       notes: [],
       fees: 1151,
       tax: 176,
       on_hold: false,
       on_hold_until: null,
       recipient_settlement_id: null,
       created_at: 1530208843 } ] }

Upvotes: 0

Views: 1348

Answers (2)

Sandeep Patel
Sandeep Patel

Reputation: 5148

check following code snippet

var data ={ entity: 'collection',
  count: 1,
  items: 
   [ { id: 'trf_Ary1cWasdfGmHAc',
       entity: 'transfer',
       source: 'pay_ASrxasdfetwhAFv',
       amount: 390000,
       currency: 'INR',
       amount_reversed: 0,
       notes: [],
       fees: 1151,
       tax: 176,
       on_hold: false,
       on_hold_until: null,
       recipient_settlement_id: null,
       created_at: 1530208843 } ] } 
       
   var id =  data.items[0].id;
   console.log(id);

Upvotes: 3

Evan Bechtol
Evan Bechtol

Reputation: 2865

You cannot read the object as data.items.id because items is an array. You have to access the specific index that you wish to get the ID for.

Example: const transfer_ID = data.items[0].id;

You could get an array of ID's by iterating over the array and storing those ID's as needed.

Upvotes: 0

Related Questions