In my JavaScript code, I am attempting to create a function that can match a specific key with an array of objects fetched from an API. This matching process is based on two parameters obtained from the API: a key (which is a string) and an array of objects containing keys and corresponding values. The desired outcome of this matching operation is to generate a new array of objects that contains the values where the provided key matches with the key in the array of objects passed as a parameter.
I have put together a sample code snippet to demonstrate what I am trying to achieve. However, the code is not functioning as intended, and I am seeking assistance on how to properly implement it. More details about the issue are provided below:
const criteriaJson = [{
"age": {
"min": "18",
"max": "65"
},
...
// Code snippet continues
}];
const question = {
key: "medicines"
};
function questionCriteriaKeyMatch(criteriaJson, question) {
criteriaJson.map((criteria) => {
return Object.keys(criteria)
.filter((key) => {
return key === question.key;
})
.reduce((cur, key) => {
return Object.assign(cur, {
criteria: criteria[key],
});
}, {});
});
}
console.log(questionCriteriaKeyMatch(criteriaJson, question));
For a better understanding of the data we are working with, the criteriaJson
variable represents an array of objects that contain sets of rules categorized into different groups (object 1 is criteria 1, object 2 is criteria 2 in this specific case).
There are essentially three scenarios for handling this data:
- When the object is empty, indicating no criteria exist to match with the key, the output is null.
- When there is only one object in the array, the match is performed on that single object, and if the key does not match, the output is null.
- In the case of having an array of multiple objects, the match needs to be done for each object individually, with the output being null if no match is found.