Skip to content
Advertisement

How to restructure parent child details in JavaScript, retrieved from database?

I am trying to display parent( Survey ) & child ( Survey participants ) details retrieved from the database ( Salesforce ).

I am using LWC ( Lightning web component ) to display the details.

There is a limitation in lwc that you can’t access data from a related object using ‘__r’ ( This means related object ) directly in HTML component.

Here is my data:

[{
"Survey_Participants__r": [
  {
    "Survey__c": "a0c55000002uRCzAAM",
    "Contact__r": {
      "Name": "Soumen Jana",
      "Id": "0035500001CBDnVAAX"
    },
    "Id": "a0d5500000Vv6DpAAJ",
    "Contact__c": "0035500001CBDnVAAX",
    "Status__c": "Sent"
  },
  {
    "Survey__c": "a0c55000002uRCzAAM",
    "Contact__r": {
      "Name": "Dhananjay Dheru",
      "Id": "0035500001CUbS5AAL"
    },
    "Id": "a0d5500000Vv6DqAAJ",
    "Contact__c": "0035500001CUbS5AAL",
    "Status__c": "Sent"
  }
],
"Id": "a0c55000002uRCzAAM",
"Batch_Id__c": "0",
"Status__c": "Sent"}]

I need to prepare it something like this :

[{
"Survey_Participants__r": [
  {
    "Survey__c": "a0c55000002uRCzAAM",
    "ContactName": "Soumen Jana",
    "Id": "a0d5500000Vv6DpAAJ",
    "Contact__c": "0035500001CBDnVAAX",
    "Status__c": "Sent"
  },
  {
    "Survey__c": "a0c55000002uRCzAAM",
    "ContactName": "Dhananjay Dheru",
    "Id": "a0d5500000Vv6DqAAJ",
    "Contact__c": "0035500001CUbS5AAL",
    "Status__c": "Sent"
  }
],
"Id": "a0c55000002uRCzAAM",
"Batch_Id__c": "0",
"Status__c": "Sent"}]

I have tried using two-approach but none of them are working as expected :

Approach 1: I am trying to use collection.map

data.map(record => Object.assign({some data manipulation here},record);

It’s not allowing to iterate through the nested structure.

Approach 2: nested data.foreach method.

Please let me know how I can fix the above issue.

Thank you in advance.

Advertisement

Answer

Here is a working stackblitz example

Advertisement