0

I have two arrays. For example something like this:

"results": [
 {
 "seen": false,
 "_id": "5f6a9608c248df5c14a6aa53",
 "user_id": "5f69264fe410854be4840e9f",
 "invited_user_id": "5f69254ee410854be4840e99",
 "createdAt": "2020年09月23日T00:25:44.314Z",
 "__v": 0
 },
 {
 "seen": false,
 "_id": "5f6a943d8d745b422cd67796",
 "user_id": "5f69264fe410854be4840e9f",
 "invited_user_id": "5f69254ee410854be4840e99",
 "createdAt": "2020年09月23日T00:18:05.634Z",
 "__v": 0
 }
 ],
 "users": [
 {
 "_id": "5f69254ee410854be4840e99",
 "name": "Paweł",
 "surname": "mnv"
 },
 {
 "_id": "5f692626e410854be4840e9c",
 "name": "Sebastian",
 "surname": "fasd"
 }
 
 ]

and now I would like to replace the "invited_user_id" form results array with user object from users array when results.invited_user_id === users._id.

What I want to get :

"results": [
 {
 "seen": false,
 "_id": "5f6a9608c248df5c14a6aa53",
 "user_id": "5f69264fe410854be4840e9f",
 "invited_user_id": {
 "_id": "5f69254ee410854be4840e99",
 "name": "Paweł",
 "surname": "mnv"
 },
 "createdAt": "2020年09月23日T00:25:44.314Z",
 "__v": 0
 },
 {
 "seen": false,
 "_id": "5f6a943d8d745b422cd67796",
 "user_id": "5f69264fe410854be4840e9f",
 "invited_user_id": {
 "_id": "5f692626e410854be4840e9c",
 "name": "Sebastian",
 "surname": "fasd"
 },
 "createdAt": "2020年09月23日T00:18:05.634Z",
 "__v": 0
 }
 ]

I could write some long function which would do that, but I am wonder if there is any faster way to do this ?

asked Sep 23, 2020 at 1:16

1 Answer 1

1

Yeah....

let data = // here put your JSON 
let results = []
data['results'].forEach(result =>{
 data['users'].forEach(user => {
 if(result.invited_user_id === user._id){
 result.invited_user_id = user
 results.push(result)
 }
 })
})
let finalData = {
 'results': results
}
console.log(finalData)

Now finalData have the JSON do you want.

answered Sep 23, 2020 at 1:40
Sign up to request clarification or add additional context in comments.

9 Comments

hm... in invited_user_id i got this : "invited_user_id": "{\n _id: 5f69254ee410854be4840e99,\n name: 'Paweł',\n surname: 'fds'\n}",. It is not a object but string...
Let me a moment, and I try to fix that part.
I don't know how you are print that, but for me it's fine, let's see imgur.com/gallery/sC7ueZ2
results and users are two different arrays in my case. It's data from data base - codesandbox.io/s/lucid-jackson-nwmub?file=/src/index.js . Maybe this is the problem... :v
result.invited_user_id = JSON.parse(user); try this...
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.