bobdolan
bobdolan

Reputation: 573

How to get specific data from object array?

I'm a beginner and would like to know how I can get a specific object from an array

I have an Array that looks like this:

data {
    "orderid": 5,
    "orderdate": "testurl.com",
    "username": "chris",
    "email": "",
    "userinfo": [
      {
        "status": "processing",
        "duedate": "" ,
      }
    ]
  },

To get the data from above I would do something like this:

return this.data.orderid

But how can I go deeper and get the status in userinfo?

 return this.data.orderid.userinfo.status

doesn't work... anyone have any ideas?

Upvotes: 1

Views: 1023

Answers (4)

flofreelance
flofreelance

Reputation: 944

You need to iterate over data.userinfo (it's an array)

var data = {
    "orderid": 5,
    "orderdate": "testurl.com",
    "username": "chris",
    "email": "",
    "userinfo": [
      {
        "status": "processing",
        "duedate": "" ,
      }
    ]
  };
  
data.userinfo.forEach(function(element) {
  console.log(element.status);
});

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)

var data = {
    "orderid": 5,
    "orderdate": "testurl.com",
    "username": "chris",
    "email": "",
    "userinfo": [
      {
        "status": "processing",
        "duedate": "" ,
      }
    ]
  };
  console.log(data.userinfo[0].status);

Upvotes: 1

bugs
bugs

Reputation: 15313

A few points:

  • data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
  • Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status

Upvotes: 2

Krypt1
Krypt1

Reputation: 1066

User Info is an array, so you would need to access it using indexer like so:

return this.data.userinfo[0].status

MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

Upvotes: 0

Related Questions