0

I am returning one map from apex controller to my aura controller js. i already have one list in my controller js. i want to find where the returned map key is present in the list or not.How can we do it. Could someone please assist me in achieving it. Tried all possible ways and not able to figure out the solution.

component code:

<aura:attribute name="enrolidMap" type="map"/>
<aura:attribute name="dataidsforOrder" type="List"/>

controller code:

var arrs = component.get("v.enrolidMap");
var newElement = component.get("v.dataidsforOrder");

var existsInArray = arrs.some(function (el) {
 return el.Id === newElement.Id;
});
if(existsInArray === false) {}

The code was not showing anything and not comparing the map and list. I have to compare the map and list whether the map key is present in the list of elements or not. Please suggest some ideas.

1 Answer 1

0

This is rather a Javascript question, which must have been answered over on StackOverflow time and again. But a cursory search hasn't produced an exact match for your question, so I'm giving it a try here!

const myMap = component.get("v.enrolidMap");
const myList = component.get("v.dataidsforOrder");

const missing0 = Object.keys(myMap).reduce(
    (prev, it) => (!myList.includes(it) ? [...prev, it] : prev), []
);

const matching0 = Object.keys(myMap).reduce(
    (prev, it) => (myList.includes(it) ? [...prev, it] : prev), []
);

const missing1 = myList.reduce(
    (prev, it) => !Object.hasOwn(myMap, it)?[...prev, it] : prev, []
);

const matching1 = myList.reduce(
    (prev, it) => Object.hasOwn(myMap, it)?[...prev, it] : prev, []
);

I've aimed at comparing map keys with lists in three more ways, to make my answer useful in more situations:

  • extracting arrays of map keys that are not in the list (missing0),
  • map keys that are in the list (matching0),
  • list elements that don't represent map keys (missing1) and
  • list elements that do (matching1).

I've made much use of Javascript's reduce method, initializing it with an empty array.

This should work for Apex return values like return Map<String, Object> or simply return Object.

(The Object.keys method applied by the first two expressions converts numbers to strings (just for the unlikely case someone does something like return Map<Object, Object>), because Javascript treats object properties as such. In case of non-text map keys, this makes the result wrong. But the use of Integers as Map keys in Apex is not something I'd recommend anyway. And you seem to process Salesforce IDs, which will work as expected.)

Does this (missing0? matching0?) work for you?

You must log in to answer this question.

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