0

I'm trying trying to "convert" a String/Text element into a list (within the same array) so I can display them as rows in my LWC Data Table. The data is retrieved from the server using Apex, and basically I'm trying to find the best way to achieve my expected output below.

Here is my SOQL query:

@AuraEnabled(cacheable=true)
    public static List<Contact> getContactRoles(Id recordId) {
        return [
            SELECT Id, Name, (SELECT Id, Roles FROM AccountContactRelations WHERE AccountId =: recordId)
            FROM Contact WHERE AccountId =: recordId
        ];
    }

If I serialize this result in JS, the data will be displayed as JSON below.

Actual Output:

[
  {
    "Id": "0031e000002Xxxxxxx",
    "Name": "James Randi",
    "AccountContactRelations": [
      {
        "Id": "07k1e000000Bxxxxxx",
        "Roles": "Scientific Skeptic;Stage Magician;TV Personality"
      }
    ]
  }
]

Expected Output:

[
  {
    "Id": "0031e000002Xxxxxxx",
    "Name": "James Randi",
    "AccountContactRelations": [
      {
        "Id": "07k1e000000Bxxxxxx",
        "Roles": [
          {
            "1": "Scientific Skeptic",
            "2": "Stage Magician",
            "3": "TV Personality"
          }
        ]
      }
    ]
  }
]

As you can see, AccountContactRelations.Roles is originally a String. What's the best way to turn the AccountContactRelations.Roles element into a list within? Manipulation could either be done in JS or Apex.

Here's what I've done, to no avail:

JS

@track contacts;

// ....

if (data) {

var sortedRoles = [];
var sort = [];
let result = JSON.parse(JSON.stringify(data));
console.log('RESULT: ' + JSON.stringify(data)); // Displays the actual output seen above 
this.contacts = result.map(function(item) {
    sort = [];
    item.AccountContactRelations.forEach(element => {
        sort.push(element.Roles);
    });

    item = [...sort];
    console.log('ITEM: ' + JSON.stringify(item)); // Displays just the roles as string
    return item;
})
}

Thanks!

UPDATED:

With resolution

let result = JSON.parse(JSON.stringify(data));
this.contacts = result.map(element => {
    element.AccountContactRelations.forEach(acc => {
        element.Roles = [...acc.Roles.split('\;')];
                        
    });

    return element;

   // Amazing
});

1 Answer 1

1

You need to spilt the Roles & it'll return an array of separated elements.

response.map(element => {
            element.AccountContactRelations.forEach(acc => {
                element.Roles = [...acc.Roles.split('\;')];
            });
        });

Which can be used the way it need to be!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .