-1

here,
res = Array of results retrieved

res = [ Object, Object, Object... Object ]

Each Object looks like this:

Object{
    "userId": "ab1ce",
    "groupId": "a1de2"
}

Now, the results has an array of objects like this, how do i access the userId present in those Objects?

Enigma297
  • 31
  • 1
  • 7

4 Answers4

1

like this:

res.forEach(function(obj){
 console.log(obj.userId);
});
Fanyo SILIADIN
  • 802
  • 5
  • 11
1

res is an array of objects so to access one object you have to use something like this:

res[index];

where index is a subscript that tell which item of the array you want. Since arrays are 0-indexed, index should be in the range [0, res.length - 1].

Then when you access an item from the array res, you'll get an object that you can access using either these ways:

res[index].key;
// OR
res[index]["key"];

where key is the name of the property of that object. So to get the userId of the first object in the array use this:

var mySecondObject = res[1]; // 0 is the first, 1 is the second ...
var theId = mySecondObject.userId; // or theId = mySecondObject["userId"];

or in one line like this:

var theId = res[1].userId;

Note: res is an array, you can loop through it using a lot of different ways (for loop, forEach ...) here is an example of how to do it.

Community
  • 1
  • 1
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

For each item of the array, 0 to n, you can get the object from the array and then access it's attributes.

for example res[0].userId would get you the userId of the first item.

you should probably read some kind of Javascript primer manual to get the basica, there're a few listed in the info page or this one is a good one

Community
  • 1
  • 1
alebianco
  • 2,475
  • 18
  • 25
0

If you're using it in loopback you can use the inq property in the where clause so as to search something from inside the Array e.g:

modelname.method({ where: { "property": { inq [ res.property  ] } } }, (err, res) => {
    if(err) { return console.error(err);
    } else {
        return true;
    }
});

The inq operator checks whether the value of the specified property matches any of the values provided in an array. The general syntax is:

{where: { property: { inq: [val1, val2, ...]}}}

Where:

property is the name of a property (field) in the model being queried.

val1, val2, and so on, are literal values in an array.

Example of inq operator:

Posts.find({where: {id: {inq: [123, 234]}}}, 
    function (err, p){... });

Answer is Specific to Loopback.

Enigma297
  • 31
  • 1
  • 7