How to access attributes of an object coming from a request with Node

Asked

Viewed 260 times

0

I have a request that returns the following:

object
{ responseHeader: 
   { status: 0,
     QTime: 0,
  response: 
   { numFound: 22,
     start: 0,
     docs: 
      [ [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object],
        [Object] ] },
  }

I wonder how I can access the attributes of each object at a time, my code so far is as follows:

var request = require('request');
request('request link', function (error, response, body) {
  console.log('error:', error);
  console.log('statusCode:', response && response.statusCode);

        var body = JSON.parse(body);
        console.log(typeof(body));

        console.log(body);

        var stringfied = JSON.stringify(body, null, 2);
        console.log(stringfied);


});

1 answer

2


You can access the property body.response.docs that will be a array. So you can go through this array:

const { docs } = body.response;

for (const doc in docs) {
   console.log(doc);
}

for...in

The for...in loop interacts over enumerated properties of an object in the original insertion order. The loop can be executed for each distinct property of the object.

Syntax

for (variavel in objeto) {...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.