I have a api (in NODEJS) response that gives back an array:
res.json(friends)
[
{
"id": 7795239,
"username": "janesmith"
},
{
"id": 1363327,
"username": "johnsmith"
}
]
But when I want to iterate through the array before sending this response, I cannot find the way to do this.
users.length
does not exist, for(var key users)
doens't work either.
How to solve this?
edit: the code where it gets the array:
User.find({}, function(err, users){
if(err) res.send(err);
var friends;
var result = 'this will hold the result';
for(var key in users){
if(users[key].username == req.decoded.username) {
friends = users[key].friends;
}
}
// here I want to do things with the list of friends, so this is the place where I need to iterate over it
res.json(result);
});
This is the log result for users
and err
users:
[
{
"_id": "5710b02c7787794009325f62",
"username": "demouser",
"__v": 0,
"friends":
[
{
"username": "janesmith",
"id": 7795239
},
{
"username": "johnsmith",
"id": 1363327
}
]
}
]
err: null
This is the log of the keys:
toObject
toJSON
items
db
discriminators
__v
id
_id
friends
password
username
userID
schema
collection
comparePassword
save
$__delta
$__version
increment
$__where
remove
model
$__buildDoc
init
$__storeShard
hook
pre
post
removePre
_lazySetupHooks
update
set
$__shouldModify
$__set
getValue
setValue
get
$__path
markModified
$__try
modifiedPaths
isModified
isDirectModified
isInit
isSelected
validate
invalidate
$__reset
$__dirty
$__setSchema
$__registerHooks
$__error
$__doQueue
$toObject
inspect
toString
equals
populate
populated
$__fullPath
domain
_events
_maxListeners
setMaxListeners
getMaxListeners
emit
addListener
on
once
removeListener
removeAllListeners
listeners
listenerCount
答案 0 :(得分:0)
Simply initialize your results variable as an array and push the users you wish to match into that array and return it.
User.find({}, function(err, users){
if (err) res.send(err);
var result = [];
for (var key in users) {
if (users[key].username == req.decoded.username) {
var friends = users[key].friends;
for (var i = 0; i < friends.length; i++) {
// Do stuff with each friend here, as required.
}
result.push(users[key]);
// OR this, depending on whether it is users or friends you're trying to return.
result.push(friends[i]);
}
}
res.json(result);
});
答案 1 :(得分:0)
似乎API的auto f = input.begin(), l = input.end();
bool ok = qi::phrase_parse(f, l, grammar, qi::space);
if (ok)
std::cout << "Parse success\n";
else
std::cout << "Parse failed\n";
if (f!=l)
std::cout << "Trailing unparsed input: '" << std::string(f, l) << "'\n";
方法正在返回一个对象而不是一个数组。
find
答案 2 :(得分:0)
var array1 = ['a', 'b', 'c'];
array1.forEach(function(element) {
console.log(element);
});
// expected output: "a"
// expected output: "b"
// expected output: "c"