user2912391
user2912391

Reputation: 67

Javascript - KEY=VALUE to object

How do you convert this kind of KEY=VALUE format to an object?

Actual:

const text = "ID=40;KEY=TEST;FI=1010;SL=100"

Expected:

{
   "ID": "40",
   "KEY": "TEST",
   "FI": "1010",
   "SL": "100",
}

Is there an easy way to do this without hazzling too much with splits?

Upvotes: 0

Views: 61

Answers (3)

Behemoth
Behemoth

Reputation: 9300

Here's my take on it using .reduce yet also .split:

const text = "ID=40;KEY=TEST;FI=1010;SL=100"

const output = text.split(";").reduce((o, key) => ({ ...o,
  [key.split("=")[0]]: key.split("=")[1]
}), {})

console.log(output)

Upvotes: 1

roanjain
roanjain

Reputation: 1252

Use this utility method to handle the JSON string in the above format without using split()

const text = "ID=40;KEY=TEST;FI=1010;SL=100";

const jsonStringToObject = (string,keySeparator,objectSeparator) => {
  const createJsonSeparator = (yourSeparator,standardSeparator) => {
    return function(jsonString){
      return jsonString.replaceAll(yourSeparator,standardSeparator);
    };
  };
  const replaceForObjectSeparator = createJsonSeparator(objectSeparator,"\",\"");
  const replaceForkeyValueSeparator = createJsonSeparator(keySeparator,"\":\"");
  const jsonStart = "{\"";
  const jsonEnd = "\"}";
  
  return JSON.parse(jsonStart+replaceForkeyValueSeparator(replaceForObjectSeparator(text))+jsonEnd);
}

console.log(jsonStringToObject(text,'=',';'));

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370669

There's nothing wrong with using .split here.

const text = "ID=40;KEY=TEST;FI=1010;SL=100"
const obj = Object.fromEntries(
  text.split(';')
    .map(substr => substr.split('='))
);
console.log(obj);

Upvotes: 5

Related Questions