Reputation: 20882
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
Upvotes: 1
Views: 188
Reputation: 45
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);
Upvotes: 1
Reputation: 326
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)
Upvotes: 1
Reputation: 370699
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);
Upvotes: 2