How can I troubleshoot my outdated JavaScript tool that is duplicating elements in an array?

Below is the input that needs to be converted into JSON format as shown:

{RS0004036}:{0;3}:{0000003AB;0000003BC}_{RS0004036}:{3;3}:{0000003DE;0000003FG}_{RS0004036}:{1;2}:{0000003HI;0000003JK}
The code should parse the above input and generate a JSON string as follows. The resulting JSON will contain a single store value at index 0 of the input string and will not repeat under partList. The desired JSON output should look like this.

"storeList": [ 
{ 
"store": "RS0004036", 
"partList": [ 
{ 
"part": "0000003AB", 
"partSub": "0000003BC", 
"qtyOnHand": "0", 
"qtyMinMax": "3" 
}, 
{ 
"part": "0000003DE", 
"partSub": "0000003FG", 
"qtyOnHand": "3", 
"qtyMinMax": "3" 
}, 
{ 
"part": "0000003HI", 
"partSub": "0000003JK", 
"qtyOnHand": "1", 
"qtyMinMax": "2" 
} 
] 
} 
] 

Here is the provided code:

const hdr_str = '{RS0004036}:{1;2}:{0000003AB;0000003BC}_{RS0004036}:{0;3}:{0000003DE;0000003FG}_{RS0004036}:{3;3}:{0000003HI;0000003JK}';;

var storeList = {}; 
var partList = []; 
storeList.partList = partList; 

//Processing 
const partsDataEntries = hdr_str.split('_'); 

for (var index = 0; index < partsDataEntries.length; index++) { 
const element = partsDataEntries[index].slice(1, -1); 
console.log('element0' + element); 
if (element != '') { 
const storepart = element.split(':'); 
const storeId = storepart[0].slice(1, -1); 
const [qtyOnHand, qtyMinMax] = element.split(':')[1].split(';');

console.log("element.split(':')[1]" + element.split(':')[1]); 
const qtyOH = qtyOnHand.substring(1, qtyOnHand.length); 
const qtyMM = qtyMinMax.substring(0, qtyMinMax.length - 1); 
const [partnum, partsub] = element.split(':')[2].split(';'); 

const part = partnum.substring(1, partnum.length); 
storeList.storeId = storeId; 

partList = { 
"partnum": part, 
"partsub": partsub, 
"qtyOnHand": qtyOH, 
"qtyMinMax": qtyMM 
} 

storeList.partList.push(partList); 
} 
} 
console.log(JSON.stringify(storeList));

The issue is with repeating elements in my tool with an outdated JavaScript engine that cannot be replaced. Can anyone suggest how to resolve it?

{"partList":[{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"},{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"},{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"}],"storeId":"RS0004036"}

Answer №1

One way to extract and store all the necessary details into specific variables/properties is by using a matching technique.

const
    data = '{RS0004036}:{1;2}:{0000003AB;0000003BC}_{RS0004036}:{0;3}:{0000003DE;0000003FG}_{RS0004036}:{3;3}:{0000003HI;0000003JK}',
    result = data
        .split('_')
        .reduce((r, s) => {
            const
                [store, qtyOnHand, qtyMinMax, part, partSub] = s.match(/[^\{\};:]+/g),
                item = { part, partSub, qtyOnHand, qtyMinMax };
            let o = r.find(o => o.store === store);
            if (o) o.partList.push(item);
            else r.push({ store, partList: [item] });
            return r;
        }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If you want to avoid using string split/slice, consider utilizing named capturing groups in a regular expression, like this:

const regex = /{(?<store>RS\d*)}:{(?<qtyOnHand>\d+);(?<qtyMinMax>\d+)}:{(?<part>.+)_(?<partSub>.+)}/gm;

You can then extract each element and retrieve the relevant property from the result of the capturing groups, for example:

let storeName = m.groups["store"];

Here is an updated snippet that extracts parts Lists and combines them into a list of stores:

const hdr_str = '{RS0004036}:{1;2}:{0000003AB;0000003BC}_{RS0004036}:{0;3}:{0000003DE;0000003FG}_{RS0004036}:{3;3}:{0000003HI;0000003JK}';
let storeList = [];

//Processing
const partsDataEntries = hdr_str.split('_');

for (var element of partsDataEntries) {
  const regex = /{(?<store>RS\d*)}:{(?<qtyOnHand>\d+);(?<qtyMinMax>\d+)}:{(?<part>.+)_{(?<partSub>.+)}/gm;
  let m;

  while ((m = regex.exec(element)) !== null) {

    let store = storeList.find(x => x.store == m.groups["store"]);
    if (store == null) {
      store = {
        "store": m.groups["store"],
        partList: []
      };
      storeList.push(store);
    }

    let part = {
      "part": m.groups["part"],
      "partSub": m.groups["partSub"],
      "qtyOnHand": m.groups["qtyOnHand"],
      "qtyMinMax": m.groups["qtyMinMax"]
    };
    store.partList.push(part);

  }
}
console.log(storeList);
console.log(JSON.stringify(storeList));

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

Using Rxjs to reset an observable with combineLatest

My scenario involves 4 different observables being combined using "combineLatest". I am looking for a way to reset the value of observable 2 if observables 1, 3, or 4 emit a value. Is this possible? Thank you! Mat-table sort change event (Sort class) Mat- ...

Error: Module not located or Image unable to load in React JS

Here is the structure of my project : src -assets fut.png -components -admin_dashboard Sidebar.js -App.js -pages Dashboard.js I encountered an issue trying to load the image fut.png from the file Sidebar.js. Even after attempting ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Using Node.js to read from a file and write the character 'Ł' to another file

I am facing an issue with an ANSI file that contains the character 'Ł'. My goal is to extract this character and save it to another file while preserving the same encoding to retain the 'Ł' character. const fs = require('fs&apos ...

When XML is accessed through an iframe, it is interpreted as HTML

In my endeavor to display an xml file within an HTML page using an iframe and altering the content through jQuery by manipulating the source attribute, I encountered a curious issue. When I viewed the xml file directly in my browser (Firefox/Chrome/IE8), i ...

I'm having trouble locating the source of the popstate loop that is generating numerous history entries

I am currently working on a project to create a dynamic webpage where the content of the main div gets replaced when certain navigation links are clicked. I have successfully implemented the pushstate function to update the div content and change the URL a ...

Implement a nested feature within the Accordion component

I am currently working on a project using Next.js and TypeScript. Within this project, I have implemented an accordion component as shown below: import React, { useEffect, useState } from 'react'; import classes from './Accordion.module.scss ...

Are there any additional features available in NetSuite that allow for viewing multiple pages within a PDF document?

I'm looking to compile a list of all available pick tickets and then consolidate them into a single PDF file. Unfortunately, I am only able to generate one page per ID. var transactionFile = render.pickingTicket({ entityId: 501, printMode: render.Pri ...

How to pass variables in AngularJS

When displaying data in a grid, I need to change the button icon on click of the active or inactive button. The functionality is working well, but I am having trouble finding the clicked active button to change its icon. In jQuery, we can use "this", but ...

Implementing autocompletion in an ASP.NET MVC4 application with AJAX and jQuery

I have been attempting to implement an autocomplete feature in a textbox that fetches company names. Despite successfully retrieving records and receiving them in the success function via Ajax, I am not seeing any suggested autocompletions in the textbox. ...

Assistance required: Click on the button to select and copy all text within the specified paragraph ID

Hey there! I've got a div with a dropdown menu that reveals text and images based on the selected option. What I want to achieve is having a button that allows users to copy all the content inside the div. Below is my sample code for the div dropdown ...

changing font size on a mobile-friendly site using javascript

Currently, I am designing a responsive webpage utilizing Bootstrap framework. Situated in the center of the screen is a text that reads: <p id="entershop" ><a class=no-deco href="shop.html">enter shop</a></p> Within the Bootstra ...

Python Selenium driver.execute_script() is not returning expected values even though a return value is provided in the JavaScript script that is passed in

I am currently facing an issue with a selenium webdriver object while using the execute_script method. Despite inputting this JavaScript script: var data = document.getElementsByClassName("assignment__row break-word clickable flex--space-between ng-st ...

Utilizing the Sheet Elite API - Step-by-Step Guide for Sending Data to a Designated Sheet Through a POST Request

Recently, I've been working on a project that involves using the Sheet Best API to submit data directly to Google Sheets. However, I'm running into an issue where the data is only being sent to the first sheet out of three. Despite having all the ...

Displaying duplicate information within a JSON ListView

My Custom ListView is pulling data from a MySQL database using JSON, but the issue I'm facing is that the list view is only displaying one entry repeatedly. How can I resolve this problem? Below is my code: package com.example.monsterking.blood; imp ...

What is the best way to store a personalized configuration for a user within a Node module?

For my CLI project in Node.js utilizing commander.js, I am interested in implementing a way to store user-specific configuration settings. This will allow users to input their preferences only once during the initial usage. What would be the best approac ...

I am running into a problem trying to configure the "timezone" setting for MySQL within Sequelize and Node.js

Currently, I am utilizing node and sequelize to develop a web API. So far, everything is functioning correctly. However, when attempting to update the user table with the following code: var localDate=getDateTime(); console.log(localDate) //output: 2021/06 ...

Triggering a JavaScript function when the mouse moves off an element

Recently, I created the following code snippet for marquee effect. The main functionality it is missing is triggering a function on mouse-over. <marquee class="smooth_m" behavior="scroll" direction="left" scrollamount="3"> <span style="float:le ...

Converting an Object with an ArrayList field to JSON and then back using Gson

I am facing a challenge with a class that has two fields. public class Sample { private String sampleString; private List<Sample2> sample2List; public Sample(String sampleString, List<Sample2> sample2List) { this.sampleStr ...

CosmosDB Update in C#: Unable to identify JSON object type for the System.String[] data structure

I need to modify a field in CosmosDB to be an array, as shown below: "Aliases": [ "John", "Johnny" ], Here is the code snippet I am using: dynamic GuideDoc= new { id = "00B2845F-F394-5E93-9A26-E70000452562", ...