Insert object to child array based on id in the child object

Viewed 88

I have conversation object as follows,

{
  "buyer": {
    "userId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
    "Name": "John"
  },
  "seller": {
    "userId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "Name": "Doe"
  },
  "conversationId": "2c418465-1154-4153-850b-4ea504877c36",
  "messages": [{
    "date": "12/23/2013",
    "text": "hi how is it going\n",
    "receiverId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "senderId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c"
  }]
}

In the above I need to replace the messages object, I need to add a new property named sender by checking the id in the conversation Object and assign it.

Output will be:

{
  "buyer": {
    "userId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
    "Name": "John"
  },
  "seller": {
    "userId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "Name": "Doe"
  },
  "conversationId": "2c418465-1154-4153-850b-4ea504877c36",
  "messages": [{
    "date": "12/23/2013",
    "text": "hi how is it going\n",
    "receiverId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
    "senderId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
    "sender": {
      "userId": "eu-central-1:1080fb20-5271-478f-97f0-0223ded70e3c",
      "Name": "John"
    },
    "reciever": {
      "userId": "eu-central-1:b3e5afe9-f4d9-4c90-b3ac-7b24a465c996",
      "Name": "Doe"
    }
  }]
}

I tried with a for loop, which works fine. But is there a way to do it in few lines using loadash or vanila javascript?

1 Answers
Related