How can one accurately pair the key and its corresponding value from an array of objects to create a new object containing only that key?

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:

  1. When the object is empty, indicating no criteria exist to match with the key, the output is null.
  2. 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.
  3. 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.

Answer №1

It seems that the goal is to transform the array into a new array containing only the values. If a key is missing, the criteria value should be set to null, otherwise it should be set to the property's value.

const criteriaJson = [{
    "age": {
      "min": "18",
      "max": "65"
    },
    "pain": {
      "min": "5"
    },
    "disease": {
      "valid": [
        "MDD",
        "PTSD"
      ],
      "invalid": [
        "None"
      ]
    },
    "medicines": "true",
    "bmi": {
      "min": "25",
      "max": "100"
    },
    "weight": "90",
    "gender": [
      "1",
      "2",
      "3"
    ],
    "pressure": "100",
    "smoker": "20",
    "zip": "^w+s{1}w+$"
  },
  {
    "age": {
      "min": "16",
      "max": "18"
    },
    "pain": {
      "max": "10"
    },
    "bmi": {
      "max": "85"
    },
    "disease": {
      "valid": [
        "none"
      ],
      "invalid": [
        "PTT",
        "ADT",
        "OLL"
      ]
    },
    "weight": "70",
    "gender": [
      "1"
    ],
    "pressure": "10"
  }
]

function extractValues (key, data) {
  if (!data?.length) return [null]
  return data.map(item => ({ value: item[key] || null }));
}

console.log('age', extractValues('age', criteriaJson));
console.log('medicines', extractValues('medicines', criteriaJson));
console.log('pressure', extractValues('pressure', criteriaJson));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the Typescript definition of a module that acts as a function and includes namespaces?

I'm currently working on creating a *.d.ts file for the react-grid-layout library. The library's index.js file reveals that it exports a function - ReactGridLayout, which is a subclass of React.Component: // react-grid-layout/index.js module.exp ...

Does the compression ratio for GZip change depending on the library used, such as Zlib in NodeJS and SharpZipLib in .Net?

Context: I am currently conducting tests on the compression ratio of our device. The data from the device is transmitted in the form of Json payloads, specifically in JArray format. I will be measuring the size of this data in Bytes before it undergoes com ...

The <form> element is giving me headaches in my JavaScript code

Trying to troubleshoot why my HTML pages render twice when I add a form with JavaScript. It seems like the page displays once with the script and again without it. Below is the basic HTML code: <form action="test.php" method="post"> <div class=" ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

Interactive sign-in/sign-out navigation bar

I need the login button to show as log out when the user is logged in. In the index.js file: app.get('/', (request, response) => { const isAuthenticated = request.session.authenticated || false; // { user: { authenticated: isAuthenti ...

Make a POST request using Express API, supporting both JSON and XML data

I am facing a unique challenge with my express API. While it typically accepts JSON post requests, there is one particular API that requires an XML post body instead. To set up my express app accordingly, I have used the following configuration: // Init ...

Tips for incorporating API-provided CSS values into AngularJS expressions for stylish card customization

I am in the process of creating unique Pokemon cards that pull data from an API. My question is, how can I apply specific CSS styling to each card directly from the API, similar to how I have utilized AngularJS to render the information? So far, I have su ...

Looking through a Json file and retrieving data with the help of Javascript

I am currently working on developing a dictionary application for FirefoxOS using JavaScript. The structure of my JSON file is as follows: [ {"id":"3784","word":"Ajar","type":"adv.","descr":" Slightly turned or opened; as, the door was standing ajar.","tr ...

I'm curious if there is a specific jQuery event that triggers right before an element loses focus or right before the next element gains focus

I am facing a situation where I have two input elements in a form that are closely connected. The first element triggers an ajax call to check for existing data in the database when the user tries to move away from it, while the second element opens a moda ...

"Using Js-ctypes to interface with a third-party DLL that returns a string

I have encountered an issue while working with a DLL using js-ctypes, which is written in C. After calling the method that returns a string and trying to access the content of the pointer, Firefox crashes! The following code snippet works perfectly: Fun ...

Using opening and closing curly braces within a PHP foreach loop

I am facing an issue with formatting an array in PHP. The array structure is as follows: Array ( [0] => Array ( [team1_score] => 10 [team2_score] => 5 [round_number] => 1 [teamtitle1] ...

What steps can be taken to resolve the error "Incompatible types: TodoItem undefined cannot be assigned to type TodoItem"?

I am currently in the process of learning TypeScript. Here is what's inside todoItem.ts: export class TodoItem { constructor( public id: number, public task: string, public complete: boolean = false ) {} printDetails(): void { ...

Numpy: Transform elements within a one-dimensional array using a dictionary

I have a sample array and dictionary provided below. >>> data = ['a', 'b', 'a', 'a'] >>> mapping = {'a': 9, 'b': 0} I am looking to apply a function that transforms np.array([& ...

Parsing precise decimal values from JSON file using Java

I have a JSON document structured like this. { "name": "Smith", "Weight": 42.000, "Height": 160.050 } To process this file, I've created the following Java code. import org.json.simple.JSONOb ...

What is the method for utilizing HSL instead of RGB in the global declaration of SCSS using the JavaScript API

This is how my next.config.js file is structured: // next.config.js const env = require('./site.config').env; const Colour = require('sass').types.Color; const {r, g, b} = require('./site.config').customProperties; const wit ...

How to Retrieve the Number of Requests in an Express Application

Is there a method to retrieve the overall count of requests in a specific route using Expressjs? ...

Remove explicit ASP.NET validation control group using JavaScript

To validate a particular group, you can utilize the following code: Page_ClientValidate('validationgroup'); If you wish to reset all validations on a page, you can use the code below: Page_ClientValidate(''); Although this method w ...

Spring MVC is set to generate JSON data but ends up displaying a web page instead

I have a method in my controller that produces a JSON payload using Spring MVC. @RequestMapping(value = "/MerchantMonitoringAPI", method = RequestMethod.GET,produces = "application/json") public String MerchantMonitoring() { ApplicationContext c ...

Preventing a scroll handler from executing once an element has been clicked

When a user scrolls to the video, it will automatically start playing. Similarly, when the user scrolls away from the video, it will stop playing and display the poster image. However, I encountered an issue where I don't want this functionality to tr ...

What is the best way to align the left div with the right div?

Here's the challenge: I want to make the left div stretch to the height of the right div https://i.sstatic.net/R3MCY.png and here's the desired outcome https://i.sstatic.net/UAXWC.png Currently, I'm implementing this using bootstrap < ...