Say i'm using @wire to return a query of multiple fields but i need to flatten out three relationship fields to display their record names

this.tableData = data.map(
                record=> Object.Assign(
                    { "SomeField1": record.SomeField1__r.Name},
                    { "SomeField2": record.SomeField2__r.Name},
                    { "SomeField3": record.SomeField3__r.Name},

The problem is sometimes those fields wont have a value and what will happen is i get an error:

[Cannot read property 'Name' of undefined]

My work around has just been never to use object assign, but that means i have to flatten out all the data. This takes more lines of code and much more time, it's fairly ugly and inconvenient. Anyone know a better way of going about this?

2 Answers 2


you can use Optional chaining (?.)

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid. The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined

for example

 { "SomeField1": record?.SomeField1__r?.Name}

furthermore, you can default it to an empty string using a Nullish coalescing operator, if the value evaluates to undefined,

{ "SomeField1": record?.SomeField1__r?.Name ?? ''}
  • There's a problem as that doesn't seem to work within the Object.Assign context, at least in LWC. You get the error [Object.Assign is not a function]]. with either method.
    – ensir
    Jul 14, 2021 at 21:15
  • 1
    @ensir It's Object.assign, not Object.Assign. JavaScript is case sensitive.
    – sfdcfox
    Jul 14, 2021 at 21:28

You can use the spread operator to make things easier, plus the null safe operator.

this.tableData = data.map(
  record => ({
    SomeField1: record.SomeField1__r?.Name,
    SomeField2: record.SomeField2__r?.Name,
    SomeField3: record.SomeField3__r?.Name

Object.Assign is not a function. JavaScript is case sensitive, so you must always take care to use exactly the correct case in the documentation.

The spread operator is roughly equivalent to Object.assign; it does not flatten an object, but it does copy all of the properties in a simple manner.

You must log in to answer this question.

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