简体   繁体   中英

NodeJS - Convert Array of Objects into Object of Objects

I'm trying to convert this data - Array of Objects

const data = [
  {
    userid: 100,
    text: 'yea',
    new: true,
    datetime: 2018-09-04T20:21:17.000Z
  },
  {
    userid: 101,
    text: 'its heading to another new year... wow the time flies...',
    new: true,
    datetime: 2018-09-03T21:51:27.000Z
  },
  {
    userid: 102,
    text: 'wish you the same ...thanks',
    new: true,
    datetime: 2018-01-12T01:36:28.000Z
  }
]

Into the following Structure - Object of Objects

{
    100: {
        userid: 100,
        text: 'yea',
        new: true,
        datetime: 2018-09-04T20:21:17.000Z
    },
    101: {
        userid: 101,
        text: 'its heading to another new year... wow the time flies...',
        new: true,
        datetime: 2018-09-03T21:51:27.000Z
      },
     102: {
        userid: 102,
        text: 'wish you the same ...thanks',
        new: true,
        datetime: 2018-01-12T01:36:28.000Z
      }
}

I've tried

messages.map((data) => ({[Math.round(new Date(data.datetime).getTime() / 1000)]: data}))

and I get the structure but map returns an array and I need an object. Been playing with reduce() - no luck yet..

thankyou

After mapping, use Object.fromEntries to turn each sub-array of [key, value] s into a property on the resulting object:

 const data = [ { userid: 100, text: 'yea', new: true, datetime: `2018-09-04T20:21:17.000Z` }, { userid: 101, text: 'its heading to another new year... wow the time flies...', new: true, datetime: `2018-09-03T21:51:27.000Z` }, { userid: 102, text: 'wish you the same...thanks', new: true, datetime: `2018-01-12T01:36:28.000Z` } ]; const obj = Object.fromEntries( data.map(obj => [obj.userid, obj]) ); console.log(obj);

This will work

 const data = [ { userid: 100, text: 'yea', new: true, datetime: `2018-09-04T20:21:17.000Z` }, { userid: 101, text: 'its heading to another new year... wow the time flies...', new: true, datetime: `2018-09-03T21:51:27.000Z` }, { userid: 102, text: 'wish you the same...thanks', new: true, datetime: `2018-01-12T01:36:28.000Z` }]; const result = {}; data.map((a) => { result[a.userid] = a; return a; }); console.log(result)

You can try this with reduce

 const data = [ { userid: 100, text: 'yea', new: true, datetime: `2018-09-04T20:21:17.000Z` }, { userid: 101, text: 'its heading to another new year... wow the time flies...', new: true, datetime: `2018-09-03T21:51:27.000Z` }, { userid: 102, text: 'wish you the same...thanks', new: true, datetime: `2018-01-12T01:36:28.000Z` }]; const a = data.reduce((acc, i) => ({...acc,[i.userid]:i}), {}) console.log(a);

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