0

I am learning LWC(newbie). I have the below situation where I want to add one additional property to an Object.

I am wiring an Apex method as below and inside loop, I am trying to add one additional property to all Contacts. Going through the Docs, I came to know that the Object is read-only.

JS File :

import { LightningElement, api, wire } from 'lwc';
import allContacts from '@salesforce/apex/contactAuraService.getAllContacts';

export default class TestPopover extends LightningElement {
    @api contacts;

    @wire(allContacts)
    cons({error, data}) {
        if(data) {
            this.contacts = data;
            this.error = undefined;
            //alert('data = '+JSON.stringify(this.contacts));
            for(let i=0; i<this.contacts.length; i++) {

                Object.defineProperty(this.contacts[i], 'short', {
                    value : this.contacts[i].Level__c.charAt(0)
                })
            }
        }
        else if(error) {
            this.contacts = undefined;
            this.error = error;
            alert('In error');
        }
    } 
}

Please help how do I add this additional property to each contact. This is my first question in here. Please excuse if anything is unclear, I will try to edit it again as required.

Thanks, Lokesh

enter image description here

4
  • Seems like you can handle this additional property within Apex itself if you wanted – Brian Miller Apr 7 '19 at 8:16
  • So, isn't possible to handle within JS ? I am trying to just get data from Apex and do data manipulation (if required) in JS – Lokesh Sagi Apr 7 '19 at 8:45
  • It's definitely possible - I believe @api makes contacts read only once it's set. Try using a temporary variable within the method @wire method itself, and then at the end assign contacts to your temporary variable (you might be able to just do it within data but not sure) – Brian Miller Apr 7 '19 at 11:38
  • 1
    I've linked one question that addresses this. You need to clone the data in order to make it mutatable. – sfdcfox Apr 7 '19 at 12:38