I am trying to write a test in JavaScript using Mocha and Chai. At the end of the test, I want to compare 2 JavaScript objects, these should be equal.
The output I get from the test is the following:
{ publication:
{ publication_id: 'pubFetch1',
title: 'Publication Fetcher',
person_id: 'uploader',
URL: 'http://www.pubfetchertest.com',
publication_year: '2015',
upload_date: '2015-05-05 00:00:00',
page_count: '5',
type: 'paper',
rating: '0',
votes: '0',
abstract: 'Testing the Publication Fetcher',
location: 'location' },
comments:
[ { commentID: 'comment1',
personID: 'uploader',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 10:24:36',
reactions: [],
myComment: true },
{ commentID: 'comment2',
personID: 'author1',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 11:01:45',
reactions: [Object],
myComment: false } ],
keywords: [ 'keyword1', 'keyword2', 'keyword3' ],
uploader: { person_id: 'uploader', first_name: 'First', last_name: 'Last' },
score: 5,
authors:
[ { person_id: 'author1', first_name: 'First', last_name: 'Last' },
{ person_id: 'author2', first_name: 'First', last_name: 'Last' },
{ person_id: 'author3', first_name: 'First', last_name: 'Last' } ],
editors: [],
publishers: [] }
While the object I want to compare it with, is the following:
{ publication:
{ publication_id: 'pubFetch1',
title: 'Publication Fetcher',
person_id: 'uploader',
url: 'http://www.pubfetchertest.com',
publication_year: '2015',
upload_date: '2015-05-05 00:00:00',
page_count: '5',
type: 'paper',
rating: '0',
votes: '0',
abstract: 'Testing the Publication Fetcher',
location: 'location'},
comments:
[{ commentID: 'comment1',
personID: 'uploader',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 10:24:36',
reactions: [],
myComment: true},
{ commentID: 'comment2',
personID: 'author1',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 11:01:45',
reactions: [{ commentID: 'comment3',
personID: 'author2',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 11:02:10',
reactions: [],
replyID: 'comment2',
myComment: false}],
myComment: false}],
keywords: ['keyword1', 'keyword2', 'keyword3'],
uploader: {person_id: 'uploader',
first_name: 'First',
last_name: 'Last'},
score: 5,
authors: [{person_id: 'author1',
first_name: 'First',
last_name: 'Last'},
{person_id: 'author2',
first_name: 'First',
last_name: 'Last'},
{person_id: 'author3',
first_name: 'First',
last_name: 'Last'}],
editors: [],
publishers: []
};
I don't see any difference in these 2 objects, so why does JavaScript say these are different? I am using JSON.stringify(obj1) === JSON.stringify(obj2) to compare these 2 objects.
JSFiddle: http://jsfiddle.net/9akeh8bh/4/
There are differences between the two objects; some keys have underscores and some are uppercase.
Have you tried standardising the key names and seeing if the comparison works?
Your reactions are different, some contain Objects, some do not.
Related
How to get data from an object? I need to get data from dataValues and write it down
const user = User.findOne({
}).then(e=>console.log(e))
User {
dataValues: {
id: 1,
firstName: 'Мен',
lastName: 'Bezrukov',
login: 'qqq',
password: '1234',
role: 'admin',
ip: '12345',
descipt: 'developer',
o_sebe: 'top man',
soc_set: 'vk',
age: '17',
likes__foto: '5',
coment__foto: null,
createdAt: 2023-01-15T09:06:39.000Z,
updatedAt: 2023-01-15T09:07:00.000Z
},
_previousDataValues: {
id: 1,
firstName: 'Мен',
lastName: 'Bezrukov',
login: 'qqq',
password: '1234',
role: 'admin',
ip: '12345',
descipt: 'developer',
o_sebe: 'top man',
soc_set: 'vk',
age: '17',
likes__foto: '5',
coment__foto: null,
createdAt: 2023-01-15T09:06:39.000Z,
updatedAt: 2023-01-15T09:07:00.000Z
},
uniqno: 1,
_changed: Set(0) {},
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [
'id', 'firstName',
'lastName', 'login',
'password', 'role',
'ip', 'descipt',
'o_sebe', 'soc_set',
'age', 'likes__foto',
'coment__foto', 'createdAt',
'updatedAt'
]
},
}
You can access directly the data by user.id, user.firstName or destructuring:
const {id,firstName} = user
another options is putting raw: true.
User.findOne({ where: {firstname: "some name"},
raw: true
})
This gives you directly an object with only the data instead of an sequelize instance.
I'm trying and puzzling for a couple of hours now and I can't get my head around it.
I have the following data structure in Redux:
entities: {
users: {
dentists: [
{
id: 1,
first_name: 'Tessa',
last_name: 'Iiannone',
phone: '+234 325 319 4277',
email: 'tiiannone0#dentistcompanybvt.com'
},
{
id: 2,
first_name: 'Kennett',
last_name: 'Pedreschi',
phone: '+48 204 144 9885',
email: 'kpedreschi1#dentistcompanybvt.com'
},
{
id: 3,
first_name: 'Lorine',
last_name: 'Tolle',
phone: '+670 691 959 9810',
email: 'ltolle2#dentistcompanybvt.com'
},
{
id: 4,
first_name: 'Nessi',
last_name: 'Pikhno',
phone: '+995 756 907 2258',
email: 'npikhno3#dentistcompanybvt.com'
}
],
assistants: [
{
id: 1,
first_name: 'Nickolas',
last_name: 'Seamans',
phone: '+62 949 597 4013',
email: 'nseamans0#dentistcompanybvt.com'
},
{
id: 2,
first_name: 'Peri',
last_name: 'Helversen',
phone: '+51 886 232 9275',
email: 'phelversen1#dentistcompanybvt.com'
}
],
clients: [
{
id: 1,
first_name: 'Mona',
last_name: 'Shakelade',
phone: '+63 475 243 2059',
email: 'mshakelade0#sourceforge.net',
date_of_birth: '26/01/1987',
status: null
},
{
id: 2,
first_name: 'Dario',
last_name: 'Aizikovitz',
phone: '+33 454 959 7355',
email: 'daizikovitz1#buzzfeed.com',
date_of_birth: '16/08/1999',
status: null
},
{
id: 3,
first_name: 'Caren',
last_name: 'Chidgey',
phone: '+358 905 256 6974',
email: 'cchidgey2#imgur.com',
date_of_birth: '08/03/1983',
status: null
},
{
id: 4,
first_name: 'Timmi',
last_name: 'Weond',
phone: '+225 796 207 5915',
email: 'tweond3#dion.ne.jp',
date_of_birth: '25/08/1972',
status: null
},
{
id: 5,
first_name: 'Greer',
last_name: 'Cornelius',
phone: '+46 793 784 2482',
email: 'gcornelius4#ask.com',
date_of_birth: '29/03/1968',
status: null
},
{
id: 6,
first_name: 'Catlee',
last_name: 'Elmar',
phone: '+33 826 857 9849',
email: 'celmar5#economist.com',
date_of_birth: '25/11/1976',
status: null
},
{
id: 7,
first_name: 'Ilsa',
last_name: 'Tynnan',
phone: '+591 283 830 4992',
email: 'itynnan6#illinois.edu',
date_of_birth: '19/02/1992',
status: null
},
{
id: 8,
first_name: 'Delia',
last_name: 'Blueman',
phone: '+55 392 389 4499',
email: 'dblueman7#printfriendly.com',
date_of_birth: '09/11/1975',
status: null
},
{
id: 9,
first_name: 'Lorilyn',
last_name: 'Semens',
phone: '+7 271 804 0493',
email: 'lsemens8#zimbio.com',
date_of_birth: '17/03/2001',
status: null
},
{
id: 10,
first_name: 'Lorilee',
last_name: 'Slemmonds',
phone: '+63 858 699 0861',
email: 'lslemmonds9#umich.edu',
date_of_birth: '20/07/1991',
status: null
}
]
},
appts: {
id: 1,
date: '01012022',
hour: 8,
client_id: 1,
dentist_id: 1,
assistant_id: 1
},
ui: {
ids: [
1
],
entities: {
'1': {
id: 1,
usertype: 'client'
}
}
}
}
}
I combined the 3 lists in my slice with:
const users = { dentists: dentists, assistants: assistants, clients: clients };
So now i expect that when i say:
const index = users.clients.indexOf((user) => user.id === action.payload.id)
...wil give me the index of the matching item with action.payload.id, but I'll keep on getting -1 when I do a console.log(index) what means that there is no match.
Can anyone help me out here?
What am I doing wrong?
indexOf requires an element. You can use find to get the element first and get the index next:
console.log(users.clients.indexOf(users.clients.find(client => client.id === action.payload.id)));
findIndex requires a callback, which is the requirement in your case, as you look for an object that you don't know, but can find by id:
console.log(users.clients.findIndex((client) => client.id == action.payload.id));
I have an object array, And in that I have roles as a key, And values init.
Now what I want is I want to group them as per the roles.
This is my data input
{
users: [
{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Theatre',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf2f0c631a8788be59fc4',
roles: [ 'ward' ],
},
{
firstName: 'Cinema',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema2',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['ward', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema4',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}
]}
AND I want to group it by roles in them and want output something like below
{
ward: [{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Theatre',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf2f0c631a8788be59fc4',
roles: [ 'ward' ],
},
{
firstName: 'Cinema2',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['ward', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}],
hospital: [
{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Cinema',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema4',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}],
hr: [{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Cinema',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema2',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['ward', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema4',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}
]
}
How can I achieve this? I am looking for a function to process this and return the output as requried.
Please find the Array.reduce implementation.
Logic
Loop through each object in array
Loop through the roles array in each object.
Check if the accumulator have a node with that role, if yes push to that node in accumulator, or else create a node with that name and current object as an element of that node
Working Example
const data = {"users":[{"firstName":"Will","lastName":"Jacob","email":"sample#sample.com","_id":"5e324187b5fdf167a91dfdbb","roles":["ward","hospital","hr"]},{"firstName":"Theatre","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf2f0c631a8788be59fc4","roles":["ward"]},{"firstName":"Cinema","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["hospital","hr"]},{"firstName":"Cinema2","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["ward","hr"]},{"firstName":"Cinema3","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["hospital","hr"]},{"firstName":"Cinema4","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["ward","hospital","hr"]}]};
const output = data.users.reduce((acc, curr) => {
curr.roles.forEach((role) => {
acc[role] ? acc[role].push(curr) : acc[role] = [curr];
})
return acc;
}, {});
console.log(output);
You can use array#reduce to group your data based on roles. You can iterate through each object and create separate array for each role type. This solution only require single traversal of your input array.
const input = { users: [ { firstName: 'Will', lastName: 'Jacob', email: 'sample#sample.com', _id: '5e324187b5fdf167a91dfdbb', roles: [ 'ward', 'hospital', 'hr' ], }, { firstName: 'Theatre', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf2f0c631a8788be59fc4', roles: [ 'ward' ], }, { firstName: 'Cinema', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: ['hospital', 'hr' ], }, { firstName: 'Cinema2', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: ['ward', 'hr' ], }, { firstName: 'Cinema3', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: ['hospital', 'hr' ], }, { firstName: 'Cinema4', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: [ 'ward', 'hospital', 'hr' ], }]},
result = input.users.reduce((r, o) => {
o.roles.forEach(role => {
r[role] ??= [];
r[role].push(JSON.parse(JSON.stringify(o)));
});
return r;
},{});
console.log(result);
You can just go over each input element and then over each role in the input element and add the element to the corresponding array in a by-role object (creating the array as needed):
const byRole = {}
for (const obj of input.users) {
for (const role of obj.roles) {
if (!byRole[role]) byRole[role] = []
byRole[role].push(obj)
}
}
console.log(byRole)
There would be also a less imperative, more functional approach, if you prefer that:
const byRole = Object.fromEntries(
[...new Set(input.users.map(obj => obj.roles).flat())]
.map(role => [role, inputArray.filter(obj => obj.roles.includes(role))])
)
console.log(byRole)
Since you seem to be working with MongoDB records, another possibility would be to group it already in your database query, offloading that work to the database server:
const queryResult = await db.users.aggregate([
// Optionally add a $match step here to filter: { $match: { ... } }
{ $addFields: { role: '$roles' } },
{ $unwind: '$role' },
{ $group: { _id: '$role', records: { $push: '$$ROOT' } } }
])
const byRole = Object.fromEntries(
queryResult.map(({ _id, records }) => [_id, records])
)
(This will leave an extra field role in each record though, but I guess you won't mind.)
const arr = [
[
{
_id: "6136096f4255d84bcb4a7144",
user_id: "5fbfa729fc46a415ce5503a6",
picture: [Array],
timestamp: 1630931311227,
},
user: {
_id: "5fbfa729fc46a415ce5503a6",
first_name: "ABC",
last_name: "AAA",
picture: [Object]
}
],
[
{
_id: "613609414255d84bcb4a7122",
user_id: "5fbf6f91aff7f3320a906547",
picture: [Array],
device_platform: 'ios',
timestamp: 1630931265409
},
user: {
_id: "5fbf6f91aff7f3320a906547",
first_name: 'EEE',
last_name: 'TTT',
picture: [Object]
}
],
[
{
_id: "613709f49223350dfdaec618",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630996980379
},
{
_id: "613609184255d84bcb4a710a",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630931224383,
},
user: {
_id: "5fbfa748fc46a415ce5503a8",
first_name: 'GRT',
last_name: 'GGG',
picture: [Object]
}
]
]
I merged push into the object one were like res = [{_id: ..., user_id: ...},{_id: ..., user_id: ...}] and other one was like user = {_id: 5fbfa748fc46a415ce5503a8, first_name: 'AAA',last_name : 'DD'}
res.user = user;
array.push(res)
I merged two object it bring up this but it does not seems to be correct response.
when I used var merged = [].concat.apply([], arr); it does not work
how to fix with correct format.
Working code! just remove the user key from the array, and one note ) use const/let instead of var
const arr = [
[
{
_id: "6136096f4255d84bcb4a7144",
user_id: "5fbfa729fc46a415ce5503a6",
picture: [Array],
timestamp: 1630931311227,
},
{
_id: "5fbfa729fc46a415ce5503a6",
first_name: "ABC",
last_name: "AAA",
picture: [Object]
}
],
[
{
_id: "613609414255d84bcb4a7122",
user_id: "5fbf6f91aff7f3320a906547",
picture: [Array],
device_platform: 'ios',
timestamp: 1630931265409
},
{
_id: "5fbf6f91aff7f3320a906547",
first_name: 'EEE',
last_name: 'TTT',
picture: [Object]
}
],
[
{
_id: "613709f49223350dfdaec618",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630996980379
},
{
_id: "613609184255d84bcb4a710a",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630931224383,
},
{
_id: "5fbfa748fc46a415ce5503a8",
first_name: 'GRT',
last_name: 'GGG',
picture: [Object]
}
]
]
const merged = [].concat.apply([], arr);
console.log(merged);
I have an array of Javascript objects like below.
[
{
email: 'alex#test.com',
fn: 'Alex',
sn: 'McPherson',
phone: '01233xxxxx',
hours: '40',
rate: '20',
amount: '200',
vat: '60',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '1234',
area: 'xzy'
},
{
id: '2345',
area: 'uhj'
}
]
}
},
{
email: 'mike#test.com',
fn: 'Mike',
sn: 'Mann',
phone: '01233xxxxx',
hours: '50',
rate: '70',
amount: '500',
vat: '90',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '1234',
area: 'xzy'
},
{
id: '3456',
area: 'uio'
}
]
}
},
{
email: 'fred#test.com',
fn: 'Fred',
sn: 'Frogg',
phone: '01233xxxxx',
hours: '80',
rate: '90',
amount: '800',
vat: '100',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '4567',
area: 'asdaf'
},
{
id: '3456',
area: 'uio'
}
]
}
},
{
email: 'alex#test.com',
fn: 'Alex',
sn: 'McPherson',
phone: '01233xxxxx',
hours: '90',
rate: '30',
amount: '900',
vat: '120',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '4567',
area: 'asdaf'
},
{
id: '5678',
area: 'asdf'
}
]
}
}
]
What I ideally want is to group those of the same value (shipping.addresses.id) into there own sub array of objects. Expected outcome.
[
{
id: '1234',
area: 'xzy',
data: [
{
email: 'alex#test.com',
fn: 'Alex',
sn: 'McPherson',
phone: '01233xxxxx',
hours: '40',
rate: '20',
amount: '200',
vat: '60',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '1234',
area: 'xzy'
},
{
id: '2345',
area: 'uhj'
}
]
}
},
{
email: 'mike#test.com',
fn: 'Mike',
sn: 'Mann',
phone: '01233xxxxx',
hours: '50',
rate: '70',
amount: '500',
vat: '90',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '1234',
area: 'xzy'
},
{
id: '3456',
area: 'uhj'
}
]
}
}
]
},
{
id: '2345',
area: 'uhj',
data: [
{
email: 'alex#test.com',
fn: 'Alex',
sn: 'McPherson',
phone: '01233xxxxx',
hours: '40',
rate: '20',
amount: '200',
vat: '60',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '1234',
area: 'xzy'
},
{
id: '2345',
area: 'uio'
}
]
}
}
]
},
{
id: '3456',
area: 'uio',
data: [
{
email: 'mike#test.com',
fn: 'Mike',
sn: 'Mann',
phone: '01233xxxxx',
hours: '50',
rate: '70',
amount: '500',
vat: '90',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '1234',
area: 'xzy'
},
{
id: '3456',
area: 'uio'
}
]
}
},
{
email: 'fred#test.com',
fn: 'Fred',
sn: 'Frogg',
phone: '01233xxxxx',
hours: '80',
rate: '90',
amount: '800',
vat: '100',
agency: 'test',
start: '08/06/2017',
end: '10/06/2017',
shipping: {
addresses: [
{
id: '4567',
area: 'asdaf'
},
{
id: '3456',
area: 'uio'
}
]
}
}
]
}
]
I can group the input array using a specific attribute using particular key (code below) but I can't seem to get my head around resorting the array based on a key which is array in itself.
Array.from(
data.reduce(
(acc, o) => (acc.get(o.email).push(o), acc),
new Map(data.map( o => [o.email, []] ))
), ([key, value]) => value
)
You can reduce the data array into an object using shipping.addresses.id as keys and return an array using Object.values(). You will need to iterate over the addresses array of each object and create an entry for each id as they are encountered and push to these entries for subsequent elements with the same id.
const byAddressId = Object.values(
data.reduce((a, o) => {
o.shipping.addresses.forEach(({id, area}) => {
a[id] = {...a[id] ?? {id: id, area: area, data: []}};
a[id]['data'].push({...o});
});
return a;
}, {}));
const data = [{"email": "alex#test.com","fn": "Alex","sn": "McPherson","phone": "01233xxxxx","hours": "40","rate": "20","amount": "200","vat": "60","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "1234", "area": "xzy" }, { "id": "2345", "area": "uhj" } ]}},{"email": "mike#test.com","fn": "Mike","sn": "Mann","phone": "01233xxxxx","hours": "50","rate": "70","amount": "500","vat": "90","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "1234", "area": "xzy" }, { "id": "3456", "area": "uio" } ]}},{"email": "fred#test.com","fn": "Fred","sn": "Frogg","phone": "01233xxxxx","hours": "80","rate": "90","amount": "800","vat": "100","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "4567", "area": "asdaf" }, { "id": "3456", "area": "uio" } ]}},{"email": "alex#test.com","fn": "Alex","sn": "McPherson","phone": "01233xxxxx","hours": "90","rate": "30","amount": "900","vat": "120","agency": "test","start": "08/06/2017","end": "10/06/2017","shipping": { "addresses": [ { "id": "4567", "area": "asdaf" }, { "id": "5678", "area": "asdf" } ]}}];
// return array of Object.values from the accumulator
const byAddressId = Object.values(
// reduce the data array into an object with shipping.addresses.id as keys
data.reduce((a, o) => {
// iterate over all addresses for each element
o.shipping.addresses.forEach(({id, area}) => {
// check if an id entry exists, otherwise create one
a[id] = {...a[id] ?? {id: id, area: area, data: []}};
// push the object to the data array of the id object
a[id]['data'].push({...o});
});
return a;
}, {}));
console.log(byAddressId);
That being said, you can use this same method to save yourself two map() calls compared to the group by email example you included in your question.
const byEmail = Object.values(
data.reduce((a, o) => (a[o.email] = [...a[o.email] ?? [], {...o}], a), {}));