Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - How do I retrieve the value of an element within an object/array

I am not sure if I have used the correct terminology within the title, but here is the raw result that I want to retrieve data from.

{ items:
   [ { name: 'keydose',
       keys: 69,
       cid: 0,
       $created': '2015-06-21T19:20:38.833Z',
   '   $updated': '2015-06-21T19:20:38.833Z' } ] }

This is created via the use of the twitch-irc-db module with the twitch-irc library for node.js, the output above is received by doing this:

db.where('users', {name: user.username}).then(function(result) {
    console.log(result);
});

I've tried using console.log(result.items.cid), console.log(result.items.cid[0]) and console.log(result.items.cid.valueOf()) to get the value of cid from the database but I have no clue what else to try, I've been googling for a long time and just can't find anything.

Thanks for your time :)

like image 492
Keydose Avatar asked Jun 21 '15 20:06

Keydose


People also ask

How do you access an element in an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };

How do you get values from array of objects in JS?

To get the values of an object as an array, use the Object. values() method, passing it the object as a parameter. The method returns an array containing the object's property values in the same order as provided by a for ... in loop. Copied!

How do you access an array of objects in Node JS?

You need to look at the structure. An Object will start with an { and an Array will start with a [ . When you see an Object, you can use . propertyName to access propertyName .


1 Answers

You need to look at the structure. An Object will start with an { and an Array will start with a [. When you see an Object, you can use .propertyName to access propertyName. For an Array, you will of course need to use an index to choose one of the objects within the Array.

So here is your response object;

{ items:
   [ { name: 'keydose',
       keys: 69,
       cid: 0,
       $created': '2015-06-21T19:20:38.833Z',
       $updated': '2015-06-21T19:20:38.833Z' } ] }

We can do result.items[0] to access the first Object within the array that items is a reference to. To get cid, we would use result.items[0].cid.

Typically, if you expect items to be more than one item, you would iterate over them with a forEach, or a for loop or a library-specific method. Using forEach, you can do:

result.items.forEach(function(item) {
  console.log(item.cid);
});
like image 197
Cymen Avatar answered Oct 29 '22 23:10

Cymen