I am attempting to dynamically pull an array via a dictionary in lwc. I am new to lwc and javascript and am having trouble getting the objects to transfer data between components.
My code is as follows:
data js
export const sectionsAndFields = {
'Approval': [{'value':1},{'value':2},{'value':3}],
'list_2': [{'value':4},{'value':5},{'value':6}]
};
reader js
import { LightningElement, api } from "lwc";
import { sectionsAndFields } from "c/data";
export default class FinancialPlanFieldFinderLayout extends LightningElement {
@api displaymarker;
sectionsAndFields = sectionsAndFields;
keyer = sectionsAndFields[this.displaymarker];
@api
get displayMarkerGetSet() {
return this._displaymarker;
}
set displayMarkerGetSet(value) {
this.setAttribute("displaymarker", value);
this._displaymarker = value;
}
reader html
<template>
<lightning-card title={displaymarker}>
<div>displaymarker: {displaymarker}</div>
<div>keyer: {keyer}</div>
<div>sectionsAndFields: {sectionsAndFields}</div>
<div>sectionsAndFields data: {sectionsAndFields.data}</div>
</lightning-card>
</template>
Of the values rendered in the reader html, I get the following:
- {displaymarker} renders
Approval
(the default value from a parent
component) - {keyer} renders nothing
- {sectionsAndFields} renders
[object Object]
- {sectionsAndFields.data} renders nothing
What I expected to happen was as follows:
- {keyer} renders
[{'value':1},{'value':2},{'value':3}]
(from data.js) - {sectionsAndFields} renders
[object Object]
- {sectionsAndFields.data} renders
[{'value':1},{'value':2},{'value':3}]
(from data.js)
Can someone help me understand why {keyer} and {sectionsAndFields.data} are returning null, and how to correct this so as to get the dictionary value from the input key?
Best Answer
Few things,
1) There is no
data
attribute in data.jssectionsAndFields
. The two attribute it has isApproval
andlist_2
. So when you try to accessdata
in markup as<div>sectionsAndFields data: {sectionsAndFields.data}</div>
would return nothing.fix: Use
Approval
orlist_2
as key.2)
keyer
should be getter as its dependent on input, had it been hardcoded values, You can just use as it likekeyer = sectionsAndFields['Approval']
and it would work. But our case is to use dynamic values, hence getter seems better option.Playground Link : https://developer.salesforce.com/docs/component-library/tools/playground/EyWz26Ub/7/edit