简体   繁体   中英

Convert array of objects to object

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.

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.

请参阅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 comment,
  etc.
}

I've had to do just this with the response from a shared form component, and it's thankfully fairly trivial to do in a one liner with some newer JS features.

const arr = [
  { name: 'Colin' },
  { length: 162 },
  { colour: 'pink' }
]

const obj = arr.reduce((acc, element) => ({...acc, ...element}))

/*
  obj = {
    name: 'Colin',
    length: 162,
    colour: 'pink'
  }
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM