How can you transfer values from one set of key/value pairs to keys of another?

I am currently dealing with the outputs of a system within my organization that I do not have control over.

Here is a sample string:

let structure = 'LAWYER=|FIRM=|SUIT_DESCRIPTION=|DEF_COMMENT=|PLF_COMMENT=|';

This string continues on, but follows this pattern.

Now, there is another string similar to the first one, but with actual data assigned to it, like in this example:

let currentData = 'FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|PLF_COMMENT=some freeform text|LAWYER=Bob Smith';

It should be noted that not all elements from structure may necessarily be found in currentData, and the order might vary (if the sequence is crucial, I can ensure they match).

My goal is to extract every element present in currentData and populate the corresponding item in structure, if it exists. Alternatively, I can add any non-matching elements from structure into currentData, ideally maintaining the same order as in structure.

Based on the provided data, the desired outcome would be:

result = 'LAWYER=Bob Smith|FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|DEF_COMMENT=|PLF_COMMENT=some freeform text|';

I am not very experienced with JavaScript :(

I attempted various methods in JSFiddle using split() and match(), but it only resulted in confusion for me.

Answer №1

// Function to transform a template into an array of keys
const getKeys = str => str.split('|').map(entry => entry.split('=')[0]);

// Function to convert data into an object
const toObj = str => Object.fromEntries(str.split('|').map(entry => entry.split('=')));

// Function to reconcile data with the template
const compile = (templateStr, dataStr) => {
  const keys = getKeys(templateStr);
  const data = toObj(dataStr);
  return keys.reduce((results, key) => {
    if(key) results.push([key, data[key] ?? '']);
    return results;
  }, []);
};

// Function to convert the results back into a string
const toString = data => data.map(entry => entry.join('=')).join('|') + '|';

// Test scenario
let template = 'LAWYER=|FIRM=|SUIT_DESCRIPTION=|DEF_COMMENT=|PLF_COMMENT=|';
let current = 'FIRM=Smith and Wesson LLP|SUIT_DESCRIPTION=It\'s a royal mess|PLF_COMMENT=some freeform text|LAWYER=Bob Smith';

console.log(toString(compile(template, current)));

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

Utilizing Semantic UI React to handle the onchange event for a textarea

(I'm a newcomer to SE, and I'll do my best to follow the community's rules and guidelines - I've searched on Google and SO but couldn't find an answer) I'm currently using the semantic-ui-react module to set up a Form with a ...

Why doesn't the let variable used in a for loop initialization extend its scope to the enclosing block?

I've always been puzzled by this question: If block scopes are generated when a let or const identifier is enclosed within curly brackets, then how come the let identifier in the initialization statement of a for loop isn't accessible in the oute ...

Attempting to pass an asynchronous initial state to the useReducer method is resulting in an undefined return value

I am facing an issue where I am fetching asynchronous data in the parent component and trying to use it as initialState in VersionContainer. However, when I pass this initialState to the context provider, the values in ContentVersionProvider end up being ...

A guide on including a node as a parameter, alongside other data types, in a function using ajax within Umbraco

When attempting to pass a node and two strings as parameters to a JsonResult in Umbraco, I encountered an issue where the node variable had no value when debugging the method. Below is the JavaScript code: function newsSub() { if(validateForm('ne ...

Generate a hard copy of the data table row without needing to view it beforehand

Here are some records from a table: +--------+---------+-------+----------+--------+ | Name | Address | Phone + Email | Action | +--------+---------+-------+----------+--------+ | Andy | NYC | 555 | <a href="/cdn-cgi/l/email-protection" cl ...

What is the best way to retrieve the nearest or preceding object regardless of the document's layout using jQuery?

Here are some examples to illustrate the concept: <ul> <li id="o1" class="elem">apple</li> <li id="o2" class="elem">banana</li> <li id="o3" class="elem">orange</li> </ul> **$('#o2').exact ...

What could be causing the issue of the function not rendering in the React app

Even though the code runs without errors in the console, the React app is not displaying any JSX content and just shows a blank page after adding an if block. Interestingly, removing the if block makes the code work as expected. import { useState } from ...

Toggle the state of a Material UI checkbox in ReactJS based on the data from hooks that return a true or checked value

I need assistance with checking/unchecking a checkbox value in an edit modal based on the return of addAdvisory(hooks) which is 'Y', indicating true/checked. Below is my basic code snippet: const [addAdvisory, setaddAdvisory] = useState({ SY ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

What is the best way to integrate LESS css into a Reactjs application?

I am looking to incorporate LESS into my React app, but I have been unsuccessful in finding a solution through Google. As a newcomer to ReactJs, I lack deep knowledge and would greatly appreciate guidance on installing Less. If anyone is able to help me ...

Using JavaScript to access private methods in Node

When working on a node application, I encountered an error when calling the _validations function. I want to make sure that _vali is kept private, even though JavaScript does not inherently support private functions. What is the recommended way to achiev ...

What is the best way to incorporate this CodePen snippet into a Vue project?

Can anyone help me figure out how to incorporate this awesome animation from CodePen (link here: https://codepen.io/iprodev/pen/azpWBr) into a Vue project? I've tried implementing it like so: <template> <div> <canvas heigh ...

Issue with JQuery TableSorter: sorting arrows are not visible

I have searched for a solution to this issue multiple times, but none of the suggested fixes seem to work for me. I have dedicated several days to figuring out how to display the sorting arrows on my table, but with no luck. I am looking to show the arrows ...

How can I dynamically remove an option from a select dropdown if it already exists in another option using jQuery?

In order to achieve the desired functionality, I need to dynamically adjust the select options based on user input. Additionally, I want the selection to update automatically upon a change event. var dynamicCount = 1; $('#add').click(function ...

Function reference in JSDoc that is not within a class context

If I have two stand-alone functions in the structure outlined below: A/foo.ts B/bar.ts Where bar.ts contains export const happy()... And foo.ts contains /** @see happy /* How can I establish the correct linkage to bar#happy? I experimented with borr ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

Tips for validating Angular form group input depending on the value of another input within the form?

I am facing an issue with form validation in my Angular version 8 application. I need to validate a form based on the following rules: If a file is uploaded (even if just clicking the button without selecting a file), then the Reason input is not required ...

Troubleshooting issues with Javascript ES6 module functionality

I'm struggling to solve a problem with my small app setup. In my project, I have an index.html file that includes a javascript file and another file named myJsModule.js in the same directory. Here's the code inside myJsModule.js: export default ...

Move items from one list to another using JavaScript

In my scenario, I have a userlist that is populated from a database. Below is the implementation of the Userlist: <select id="Userlist" name="cars" runat="server" multiple="true" style="width: 270px; height: 200px;"> </select> The objective i ...

React Native: Picker value remains static

I'm encountering an issue where the value of the picker does not change when I select a new value from it. This problem started occurring after I added the onValueChange function. If anyone has any insights or suggestions on how to resolve this, I wou ...