What is the best way to extract values from a string that are already mapped

Recently, I encountered this string:

const string =
    "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";

My goal is to extract the keys and values like this:

DEVICE_SIZE: ["036", "048", "060", "070"]

Here's what I have so far:

  const string =
    "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";

  const res = string.split('IN ');

  const regExp = /\(([^)]+)\)/;

  const Y = 'AND';

  const data = res.map((item) => {
    if (regExp.exec(item)) {
      return {
        [item.slice(item.indexOf(Y) + Y.length)]: regExp.exec(item)[1],
      };
    }
  });

  console.log('data ', data);

Desired Outcome:

[
  { "DEVICE_SIZE": ["036", "048", "060", "070"] },
  { "DEVICE_VOLTAGE": ["1", "3"] },
  { "NOT DEVICE_DISCHARGE_AIR": ["s"] },
  { "NOT DEVICE_REFRIGERANT_CIRCUIT": ["H", "C"] },
];

I attempted to achieve the expected outcome but fell short. Could someone please assist me in reaching the result mentioned above?

Note: My previous question on a similar topic can be found at How to get valid object from the string matching respective array?

Answer №1

Utilizing a single regex with 2 capture groups is the way to match both the key and the value effectively.

((?:\bNOT\s+)?\w+)\s+IN\s+\('([^()]*)'\)

Feel free to check out the regex demo.

The provided pattern captures:

  • ( Capturing group 1
    • (?:\bNOT\s+)? Optionally matching the word NOT followed by at least 1 whitespace character
    • \w+ Matching one or more word characters
  • ) Closing group
  • \s+IN\s+ Matching the word IN surrounded by whitespace characters
  • \(' Matching ('
  • ([^()]*) Capturing group 2, matching one or more occurrences of any character except ( and )
  • '\) Matching ')

To generate dynamic keys for the object, you can utilize the Object Initializer and split on ',' to form the resulting array for the value.

const regex = /((?:\bNOT\s+)?\w+)\s+IN\s+\('([^()]*)'\)/g;
const string = "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";
const data = Array.from(
string.matchAll(regex), m =>
({
[m[1]]: m[2].split("','")
})
);
console.log(data);

Answer №2

One method to parse this data is by first splitting the string using the AND keyword, and then further splitting each result using the IN clause to isolate the key-value pairs.

Alternatively, you can achieve the same outcome with the following code snippet:

const stringData =
  "DEVICE_SIZE IN ('036','048','060','070') AND DEVICE_VOLTAGE IN ('1','3') AND NOT DEVICE_DISCHARGE_AIR IN ('S') AND NOT DEVICE_REFRIGERANT_CIRCUIT IN ('H','C')";

const parsedOutput = stringData
  .split("AND")
  .map((item) => item.split("IN").map((text) => text.trim()))
  .map(([key, value]) => ({
    [key]: value.replace(/[\(\)\']/g, "").split(","),
  }));

console.log(parsedOutput);

Answer №3

If you want to convert key-value pairs in the form of tuples [string, any] into an object, use the method Object.fromEntries:

const result = Object.fromEntries(data.map((element) => {
    if (testRegex.test(element)) {
      return [element.slice(element.indexOf(X) + X.length).trim(), testRegex.exec(element)[1].split(',').map(val => val.slice(1, -1))];
    }
    return undefined;
}).filter(Boolean));

After that, you can proceed with your task.

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 best way to assign Reference Identification numbers to the orders?

Is there a way for me to obtain and attach the id reference to the order? I have retrieved the product and user ids. When I utilize my get method, it should retrieve all the details about the products and users. For instance, the data will display compreh ...

Creating a multi-step progress bar in Yii2 that showcases completed steps using jQuery

Is there a way to automatically transition from one state to another once the order status changes in Yii2? var i = 1; $('.progress .circle').removeClass().addClass('circle'); $('.progress .bar').removeClass().addClass(&a ...

Dynamic text displayed on an image with hover effect using JavaScript

Currently, I am in the process of developing a website for a coding course that is part of my university curriculum. The project specifications require the use of JavaScript, so I have incorporated it to display text over images when they are hovered over ...

Attempting to generate a cost estimator, however, no results are showing up upon clicking the calculate button

Having based my code on a template and being fairly new to Javascript, I expected everything to work smoothly. However, upon testing it, I encountered an issue where nothing was displayed in the results boxes. My goal is to develop a pricing calculator th ...

jquery-validation error in gulp automations

I've encountered a sudden error in my gulp build related to jQuery validation. There haven't been any recent changes that would trigger this issue. Interestingly, one of my colleagues is experiencing the same problem, while another one is not. We ...

There is a lack of 'Access-Control-Allow-Origin' header - Issue encountered while making Food2Fork API request using AJAX

Our team has just embarked on our first project, and I've encountered a roadblock while conducting API testing. Specifically, I am struggling to generate a successful access control header. Is there anyone who can provide assistance in troubleshooting ...

Enhancing React Flow to provide updated selection and hover functionality

After diving into react flow, I found it to be quite user-friendly. However, I've hit a roadblock while attempting to update the styles of a selected node. My current workaround involves using useState to modify the style object for a specific Id. Is ...

The lack of a defined theme in the makeStyles for @mui/styles sets it apart from @material-ui/core

Struggling to update my material-ui from version 4.11 to version 5 and running into problems with themes. import { createTheme } from '@mui/material/styles'; import { ThemeProvider, StyledEngineProvider, } from '@mui/material/styles&apo ...

eBay API request error: "You do not have the necessary permissions to complete the request."

While working on integrating the eBay API, I encountered an issue with creating a payment policy. Following the instructions provided in this guide , I generated a token and sent it using Postman. However, I received an error: { "errors": [ ...

Tips for cutting out specific sections of a URL displayed in the browser's address bar

I have been attempting to manipulate the URL in the address bar using JavaScript. Although the result is correct when I test it in the console, it doesn't seem to update in the address bar. What could be causing this issue? Is there a different appr ...

What is the best way to update a specific column value in a table using AngularJS?

How can I achieve opening a specific row's text-area when clicking the "Add_Note" button inside a table column, without affecting all other rows? I want to show them using index value while using ng-repeat. var myApp = angular.module('myApp&ap ...

Retrieve the value from every dynamically generated text box by its corresponding number

Trying to create a new Online Quiz System. The challenge I'm facing is extracting the values of each option associated with a specific question number. For example: Question # 1: a. elephant b. lion c. zebra Question # 2: a. green b. ...

Is it safe to enable HTTPS on my Glitch project even if my app is currently set up to use HTTP only?

I successfully created an http express app and placed it on glitch. Here is the code: const app = require('express')(); const express = require('express'); const http = require('http').createServer(app); app.use(express.stat ...

Integrating new information into an existing JSON file using React Native

Currently, I am attempting to input new data into an existing JSON file using text input. In my project using React Native, I have a JSON file named PartyInfo.json where certain data is stored. The goal is to have this data passed from a form and saved in ...

Efficiently map nested properties of this.props within the render method

When working in the render() method, I find myself passing numerous variables around. The recommended best practices suggest setting up variables before the return <div>...etc</div statement like this: const { products: mainProducts, ...

The concept of selective importing within JavaScript

Seeking guidance on configuring conditional imports for a native library that is built for both node and electron. The challenge arises when one project requires the node implementation for testing, while another project needs the electron version. Projec ...

Issues with Firefox Protractor testing functionality

Trying to test a protractor on an angularjs application using Firefox 47 has been unsuccessful. Attempted downgrading to version 46.0.1 after researching on Stack Overflow, but still facing issues. Has anyone discovered a working solution for this? It seem ...

AngularJS $http.get('') is throwing an error because some parameters are missing

I am currently working on an application that utilizes OAuth for authentication, but I am facing some issues with passing the URL parameters correctly. Despite trying various methods, my API keeps returning an error stating that the username and password a ...

An effective method for retrieving the version from package.json

I am currently in the process of developing an SDK that will soon be available on npm. One of the requirements for this SDK is to deliver its version to the client. My goal is to have this version match the one specified in the package.json file. However ...

When attempting to retrieve data in a server-side component, Next.js encountered an ECONNREFUSED error with ::1:3000

import React from "react"; import axios from "axios"; interface UsersType { id: string; firstName: string; lastName: string; email: string; } interface dataProps { allUsers: UsersType[]; } async function getData() { try { c ...