admin管理员组

文章数量:1391977

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.

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.

Share Improve this question edited Sep 29, 2012 at 19:32 JohnnyHK 312k69 gold badges631 silver badges476 bronze badges asked Sep 29, 2012 at 14:07 Diogo MendonçaDiogo Mendonça 4882 gold badges7 silver badges20 bronze badges 2
  • 4 You probably can't find an example, because there's no reason to do it. – I Hate Lazy 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. – jwchang Commented Sep 29, 2012 at 18:44
Add a ment  | 

3 Answers 3

Reset to default 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.

See the object function of underscore.js.

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 ment,
  etc.
}

本文标签: javascriptConvert array of objects to objectStack Overflow