3

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.

2
  • 4
    You probably can't find an example, because there's no reason to do it. Commented Sep 29, 2012 at 14:10
  • Think a "person" is an JSON object and think array as group of those people. Just iterate(ex: for loop) those array and do whatever you want to do with each person. Commented Sep 29, 2012 at 18:44

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Won't that make it harder for my client application to parse the result ?
All JSON parsers can (hopefully) parse and return arrays just fine, since a top-level array is valid JSON.
1

See the object function of underscore.js.

4 Comments

Technically this a solution for something, but in this case it's the opposite of a useful answer.
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.
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.
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.
0

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.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.