In my node REST application I have a function that queries a database for several records and returns an array of objects.
Since I want it to return a JSON object, I need a way to convert the array of objects to a single object with all the records inside.
Unfortunately I can't find an example on the internet about doing something like this.
Any help would be appreciated.
3 Answers
Why would you want to do that ? Its totally fine to JSON stringify an Array of items, you'll get a structure like
"[{},{},{},...]"
that is probably even an advantage, because you keep the order of items guaranteed.
2 Comments
Diogo Mendonça
Won't that make it harder for my client application to parse the result ?
jonvuri
All JSON parsers can (hopefully) parse and return arrays just fine, since a top-level array is valid JSON.
See the object function of underscore.js.
4 Comments
jonvuri
Technically this a solution for something, but in this case it's the opposite of a useful answer.
Golo Roden
I think the decision whether this answer is useful or not can best be made by the original author of the question. He asked how to convert an array to an object, so I told him how. He did not ask whether this is the best way of how to deal with his situation. Hence no need to get rude IMHO.
jonvuri
I'm sorry if I came across as disrespectful, that wasn't my intention. I do think it's a bad answer, because while the OP did ask how to convert an array to an object, that was not the best solution for what they were actually trying to accomplish, and doing it anyway most likely would have introduced other problems and confusion. It's best to try to answer to the overarching goal, rather than the literal question.
Paul
Underscore's
object function converts an array of arrays or two arrays into an object. It does not convert an array of objects into an object.Lets assume you have an array of objects with the form:
log {
name: "foo",
log: "bar"
}
Your could do:
var logs,//Array of logs
logObj = {}
for(i=0, i<logs.Length i++) {
logObj[logs[i].Name] = logs[i].log;
}
After the loop logObj should be:
logObj {
foo: bar,
nextName: cool comment,
etc.
}
JSON objectand thinkarrayas group of those people. Just iterate(ex: for loop) those array and do whatever you want to do with each person.