javascript - Convert array of objects to object - Stack Overflow

In my node REST application I have a function that queries a database for several records and returns a

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744694621a4588416.html

相关推荐

  • javascript - Convert array of objects to object - Stack Overflow

    In my node REST application I have a function that queries a database for several records and returns a

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信