Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Assign values from one set of key/value pairs to keys of another?

I'm working with the outputs of an Intranet I don't control.

I have this string:

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

It goes on longer, but that's the pattern.

Now there's another similar string, but with data assigned, as in this example:

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

Now, notice that not every element in template is necessarily represented in current, and the order may be different (if the latter fact is a big deal, I can ensure the order is the same).

What I'm trying to do, is take every element that is in current, and populate the matching element in template, if it exists. (or, alternatively and potentially preferred, insert every non-matching element in template into current, but ideally in the same order as template).

Using the date above, the result I'm looking for is:

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

I'm not very accomplished with JavaScript :(

I tried various things in JSFiddle using split() and match() but I just made a mess of it.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

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

// Reconcile the 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;
  }, []);
};

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

// And then a test
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)));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!