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);
Related
I have a prisma query that returns users on a pivot table CommunityMember. The pivot table associates to the table User. As a result, my queries into the User table do not place the object user on top of the replies. I have a lot of functions designed to run with the user object on top so I am trying to figure out how to map user into my returns so the functions can run correctly. I've tried a lot of combinations of map and have had no luck. Do you all have any ideas?
Here is my prisma query:
members = await prisma.user.findMany({
select: {
id: true,
username: true,
name: true,
bio: true,
avatar: true,
},
skip: 10 * Number(page),
take: 10,
});
It gives a result like
members:
[{id: 2, username: 'man}, {id: 3, username: 'dan'}]
I want it to look like: members:
members:
[{user: {id: 2, username: 'man'}}, {user: {id: 3. username: 'dan'}}]
If I run members[0].user I should get the data inside. It seems like a simple map function, but I have not been able to get it to work.
Another example of what I get, but do not want.
members: [
{
id: 2,
username: 'man',
name: 'A Man',
bio: 'A man.',
avatar: [Object]
},
{
id: 3,
username: 'dude',
name: 'Dude',
bio: "Dude is a #1 developer.",
avatar: [Object]
},
This is what I want.
members: [
{
//Notice the user object on top of each entry
user: {
id: 2,
username: 'man',
name: 'A Man',
bio: 'Man.',
avatar: [Object]
}
},
{
user: {
id: 3,
username: 'dude',
name: 'Dude',
bio: "Dudes a #1 developer.",
avatar: [Object]
}
},
]
Not sure I got the whole picture but wouldn't this do?
const members = [
{
id: 2,
username: 'man',
name: 'A Man',
bio: 'A man.',
avatar: {}
},
{
id: 3,
username: 'dude',
name: 'Dude',
bio: "Dude is a #1 developer.",
avatar: {}
}
].map(member => ({user: member}))
if your object looks like:
obj = {members: [{...}, ..]}
then an Array.map will solve the problem:
const userMembers = obj.members.map((member) => ({user: member});
obj.members = userMembers;
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 building a chat application and have an array of chats which contains an array of users:
[
{
_id: 'chatId1',
createdAt: 'createdDate',
latestMessage: {_id: 'someId', sender: {...}, content: 'someContent', ...},
updatedAt: 'updatedDate',
users: [
{_id: 'userId1', name: 'userName1'},
{_id: 'userId4', name: 'userName4'}
},
{
_id: 'chatId2',
createdAt: 'createdDate',
latestMessage: {_id: 'someId', sender: {...}, content: 'someContent', ...},
updatedAt: 'updatedDate',
users: [
{_id: 'userId1', name: 'userName1'},
{_id: 'userId2', name: 'userName2'}
},
{
_id: 'chatId3',
createdAt: 'createdDate',
latestMessage: {_id: 'someId', sender: {...}, content: 'someContent', ...},
updatedAt: 'updatedDate',
users: [
{_id: 'userId1', name: 'userName1'},
{_id: 'userId3', name: 'userName3'}
},
]
And a separate array of users:
[
{_id: 'userId1', name: 'userName1'},
{_id: 'userId2', name: 'userName2'},
{_id: 'userId3', name: 'userName3'},
{_id: 'userId4', name: 'userName4'}
]
The recurring user in chats, userName1 will be the logged in user.
My chats array is already sorted by updatedAt when they are fetched from the backend so the most recent chat is at the top.
What I'm trying to do is arrange my users array so that they match the order that the unique user appears in the chats array which can be updated as messages get sent.
This is what I have tried so far:
const usersToSort = [];
chats.map((c) => {
usersToSort.push(c.users.filter((u) => u._id !== userId1));
});
const sorted = [].concat.apply([], usersToSort);
By filtering out the logged in user and pushing the unique user's id into an empty array I can order the users the way I need to, however the problem with this is that it empties the chats array of the user who is receiving the message as they have a completely different array of users so I need to find another way of doing this.
Have been working at it for some time now and still coming up stuck.
// Input params.
const chats = [
{
_id: 'chatId1',
createdAt: 'createdDate',
latestMessage: {_id: 'someId', sender: {}, content: 'someContent'},
updatedAt: 'updatedDate',
users: [
{_id: 'userId1', name: 'userName1'},
{_id: 'userId4', name: 'userName4'}
]
},
{
_id: 'chatId2',
createdAt: 'createdDate',
latestMessage: {_id: 'someId', sender: {}, content: 'someContent'},
updatedAt: 'updatedDate',
users: [
{_id: 'userId1', name: 'userName1'},
{_id: 'userId2', name: 'userName2'}
]
},
{
_id: 'chatId3',
createdAt: 'createdDate',
latestMessage: {_id: 'someId', sender: {}, content: 'someContent'},
updatedAt: 'updatedDate',
users: [
{_id: 'userId1', name: 'userName1'},
{_id: 'userId3', name: 'userName3'}
]
}
];
const users = [
{_id: 'userId1', name: 'userName1'},
{_id: 'userId2', name: 'userName2'},
{_id: 'userId3', name: 'userName3'},
{_id: 'userId4', name: 'userName4'}
];
// Result.
const sortedUsers = chats
.map(v => v.users)
.flat()
.reduce((t, v) => [...t, ...(t.some(i => i._id === v._id) ? [] : [v])], []);
console.log(sortedUsers);
I am trying to add an User object to my Game object's field "players_list", which is a list of User objects. This is what my Game object looks like:
{ players_list:
[ { games: [Array],
_id: '5b0e112ff13033792f08566f',
email: 'c',
password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
handle: 'C',
__v: 0,
id: '5b0e112ff13033792f08566f' } ],
_id: '5b0e181aeb766e7bfaf2fb09',
players_status:
[ { _id: '5b0e181aeb766e7bfaf2fb0a',
playerId: '5b0e112ff13033792f08566f',
status: 'Joined' } ],
postGameEvaluation: [],
date: 'QQQQ',
time: 'QQQQ',
duration: 4,
players_needed: 4,
max_players: 4,
level: 4,
author:
{ games:
[ '5b0e13e69d35007a147578da',
'5b0e15b4b117987b00d68cb4',
'5b0e181aeb766e7bfaf2fb09' ],
_id: '5b0e112ff13033792f08566f',
email: 'c',
password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
handle: 'C',
__v: 0,
id: '5b0e112ff13033792f08566f' },
__v: 0 }
and this is what my User objet looks like
{ games: [],
_id: 5b0e1820eb766e7bfaf2fb0b,
email: 'f',
password: '$2a$10$JmS.9axW8batMUKzE7OQx.GShdNDt09eArXfYGoI/DUWEKVwAn5ju',
handle: 'F',
__v: 0 }
I then run req.body.players_list.push(req.user) to add the User object to the player_list field of the Game object. This is what by req.body looks like after adding the User object:
{ players_list:
[ { games: [Array],
_id: '5b0e112ff13033792f08566f',
email: 'c',
password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
handle: 'C',
__v: 0,
id: '5b0e112ff13033792f08566f' },
{ games: [],
_id: 5b0e1820eb766e7bfaf2fb0b,
email: 'f',
password: '$2a$10$JmS.9axW8batMUKzE7OQx.GShdNDt09eArXfYGoI/DUWEKVwAn5ju',
handle: 'F',
__v: 0 } ],
_id: '5b0e181aeb766e7bfaf2fb09',
players_status:
[ { _id: '5b0e181aeb766e7bfaf2fb0a',
playerId: '5b0e112ff13033792f08566f',
status: 'Joined' } ],
postGameEvaluation: [],
date: 'QQQQ',
time: 'QQQQ',
duration: 4,
players_needed: 4,
max_players: 4,
level: 4,
author:
{ games:
[ '5b0e13e69d35007a147578da',
'5b0e15b4b117987b00d68cb4',
'5b0e181aeb766e7bfaf2fb09' ],
_id: '5b0e112ff13033792f08566f',
email: 'c',
password: '$2a$10$iWOBvVf4KAPwbH7zDczfYeI5iXI721jQ7bN1juJ4Us3R.Lqetmhfu',
handle: 'C',
__v: 0,
id: '5b0e112ff13033792f08566f' },
__v: 0 }
So, I then update the Game object in mongo with Post.findByIdAndUpdate(req.params.id, req.body).then((result) => {..., but the result doesn't contain the new User. This is what my result looks like
{ players_list: [ 5b0e112ff13033792f08566f ],
_id: 5b0e181aeb766e7bfaf2fb09,
players_status:
[ { _id: 5b0e181aeb766e7bfaf2fb0a,
playerId: '5b0e112ff13033792f08566f',
status: 'Joined' } ],
postGameEvaluation: [],
date: 'QQQQ',
time: 'QQQQ',
duration: 4,
players_needed: 4,
max_players: 4,
level: 4,
author: 5b0e112ff13033792f08566f,
__v: 0 }
The strange thing is that if I leave my current React Component, and then go back into it (thus triggering fetchUser and fetchGame), then the Game fetched does have the new User in its players_list. Does this happen because the mongo update function is asynchronous? Even so, I thought that the .then((result) => { in Post.findByIdAndUpdate(req.params.id, req.body).then((result) => { made sure that Post.findByIdAndUpdate completed first before continuing
If you look at the docs: http://mongoosejs.com/docs/api.html#findbyidandupdate_findByIdAndUpdate you'll notice that findByIdAndUpdate returns the original object, not the updated doc. You have to pass in {new: true} as options for it to resolve with the updated object.
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.