Search code examples
javascriptsalesforcelwc

Loop the JSON String using filter function by passing array values, Javascript


[
  {
    "dataType": "BOOLEAN",
    "name": "checkbox_confidential",
    "isCollection": false,
    "flowName": "FlowData",
    "value": true,
    "objectType": null
  },
  {
    "dataType": "BOOLEAN",
    "name": "checkbox_password",
    "isCollection": false,
    "flowName": "FlowData",
    "value": false,
    "objectType": null
  },
  {
    "dataType": "BOOLEAN",
    "name": "checkbox_restriction",
    "isCollection": false,
    "flowName": "FlowData",
    "value": true,
    "objectType": null
  },
  {
    "dataType": "DATEONLY",
    "name": "date_dateReq",
    "isCollection": false,
    "flowName": "FlowData",
    "value": "2022-10-30",
    "objectType": null
  }]

I am getting the above JSON from the flow to LWC. I am capturing the above Json to a variable called outputVariables from event.detail;

let { outputVariables, status } = event.detail;
_searchOutputVariables = ['checkbox_restriction','date_dateReq'];

const result = outputVariables.filter(outvar => outvar.name == "checkbox_restriction");
  if(result != undefined && result.length > 0){
     this.restrictionLocal = result[0].value;
  }

I am trying to get the value by passing each variable like the above. But my lead wants me to create an array and add all the filter text and pass to the filter function. I create an array '_searchOutputVariables'. how to use that array in filter function? please help me to do this?




Solution

  • It is pretty easy:

    const outputVariables = [
      {
        "dataType": "BOOLEAN",
        "name": "checkbox_confidential",
        "isCollection": false,
        "flowName": "FlowData",
        "value": true,
        "objectType": null
      },
      {
        "dataType": "BOOLEAN",
        "name": "checkbox_password",
        "isCollection": false,
        "flowName": "FlowData",
        "value": false,
        "objectType": null
      },
      {
        "dataType": "BOOLEAN",
        "name": "checkbox_restriction",
        "isCollection": false,
        "flowName": "FlowData",
        "value": true,
        "objectType": null
      },
      {
        "dataType": "DATEONLY",
        "name": "date_dateReq",
        "isCollection": false,
        "flowName": "FlowData",
        "value": "2022-10-30",
        "objectType": null
       }
     ];
     
    const _searchOutputVariables = ["checkbox_restriction", "date_dateReq"];
    
    const result = outputVariables.filter(node => {
      if (_searchOutputVariables.includes(node.name))
        return node;
    });
    
    console.log(result);