Create an array of strings in the format of key-value pairs

Incoming data needs to be transformed into key value pairs:

SECRET_TOKEN=Iwillruletheworld;SECRET_REFRESH_TOKEN=Iwillruletheworld;SERVER_PORT=3000;SERVER_WS_PORT=4000;NODE_URI=http://test.abc.com/#/;MONGODB_DEFAULT_URI=mongodb;MONGODB_HOST=localhost;MONGODB_PORT=27017;

To start, separate the data using ;:

data.split(';');

Current Output

[ 'SECRET_TOKEN=Iwillruletheworld',
  'SECRET_REFRESH_TOKEN=Iwillruletheworld',
  'SERVER_PORT=3000',
  'SERVER_WS_PORT=4000',
  'NODE_URI=http://test.abc.com/#/',
  'MONGODB_DEFAULT_URI=mongodb',
  'MONGODB_HOST=localhost',
  'MONGODB_PORT=27017'
]

The goal now is to convert it into key value pairs:

Expected Output

[ 'SECRET_TOKEN'='Iwillruletheworld',
  'SECRET_REFRESH_TOKEN'='Iwillruletheworld',
  'SERVER_PORT'='3000',
  'SERVER_WS_PORT'='4000',
  'NODE_URI'='http://test.abc.com/#/',
  'MONGODB_DEFAULT_URI'='mongodb',
  'MONGODB_HOST'='localhost',
  'MONGODB_PORT'='27017'
]

A task remains - inserting ' wherever = appears. Assistance would be appreciated.

Answer №1

If you prefer the output to be an object (since the provided output is invalid), one approach is to split by ;, remove empty items (.filter(Boolean)), and use reduce to create a key-value pair object.

This method assumes there are no duplicate keys in the input.

let input = `SECRET_TOKEN=Iwillruletheworld;SECRET_REFRESH_TOKEN=Iwillruletheworld;SERVER_PORT=3000;SERVER_WS_PORT=4000;NODE_URI=http://test.abc.com/#/;MONGODB_DEFAULT_URI=mongodb;MONGODB_HOST=localhost;MONGODB_PORT=27017;`;

let res = input.split(';').filter(Boolean).reduce((acc, next) => {
  let [key, value] = next.split('=');
  acc[key] = value;
  return acc;
}, {});

console.log(res);

Edit (2021): Another more "modern" solution involves using Object.fromEntries instead of .reduce. The result remains the same, just with a slightly different approach.

let input = `SECRET_TOKEN=Iwillruletheworld;SECRET_REFRESH_TOKEN=Iwillruletheworld;SERVER_PORT=3000;SERVER_WS_PORT=4000;NODE_URI=http://test.abc.com/#/;MONGODB_DEFAULT_URI=mongodb;MONGODB_HOST=localhost;MONGODB_PORT=27017;`;

const mapEntries = Object.fromEntries(
  input.split(';').filter(Boolean).map(v => v.split('='))
);
console.log(mapEntries);

Answer №2

One way to convert it into a JavaScript object (not an array) is:

var arr = [ 'SECRET_TOKEN=Iwillruletheworld',
  'SECRET_REFRESH_TOKEN=Iwillruletheworld',
  'SERVER_PORT=3000',
  'SERVER_WS_PORT=4000',
  'NODE_URI=http://test.abc.com/#/',
  'MONGODB_DEFAULT_URI=mongodb',
  'MONGODB_HOST=localhost',
  'MONGODB_PORT=27017'
];

var obj = {};

arr.forEach((x) => {
  var kv = x.split('=');
  obj[kv[0]] = kv[1];
});

console.log(obj);

Answer №3

To parse the string and convert it into an object, you can split the string using ';' as delimiter, then further split each part using '=' as delimiter. Next, you can create an array of objects by mapping over the splitted parts and use Object.assign to merge them into a single object.

let str = 'SECRET_TOKEN=Iwillruletheworld;SECRET_REFRESH_TOKEN=Iwillruletheworld;SERVER_PORT=3000;SERVER_WS_PORT=4000;NODE_URI=http://test.abc.com/#/;MONGODB_DEFAULT_URI=mongodb;MONGODB_HOST=localhost;MONGODB_PORT=27017';
let out = Object.assign({}, ...str.split(';').map(e => ({[e.split('=')[0]]: e.split('=')[1]})));
console.log(out)

Answer №4

let info = 'TOP_SECRET_KEY=Iamtheboss;SECRET_REFRESH_TOKEN=Ihavethepower;SERVER_PORT=3000;SERVER_WS_PORT=4000;NODE_URI=http://supersecret.com/#/;MONGODB_DEFAULT_URI=mongodb;MONGODB_HOST=localhost;MONGODB_PORT=27017';
//assuming the information you receive is a collection of strings

let dataArr = info.split(';');
let infoObj = {};
for (let item of dataArr){
   let splitItem = item.split('=');
   infoObj[splitItem[0]] = splitItem[1];
}
console.log(infoObj);

Answer №5

Here is a code snippet to create an array of strings:

const str = 'SECRET_TOKEN=Iwillruletheworld;SECRET_REFRESH_TOKEN=Iwillruletheworld;SERVER_PORT=3000;SERVER_WS_PORT=4000;NODE_URI=http://test.abc.com/#/;MONGODB_DEFAULT_URI=mongodb;MONGODB_HOST=localhost;MONGODB_PORT=27017;'
const strArray = str.split(';');
const corrArray = strArray.map(s=> s.replace('=', "'='")).map(s=> `'${s}'`);
console.log(corrArray);

If you prefer objects instead:

const str = 'SECRET_TOKEN=Iwillruletheworld;SECRET_REFRESH_TOKEN=Iwillruletheworld;SERVER_PORT=3000;SERVER_WS_PORT=4000;NODE_URI=http://test.abc.com/#/;MONGODB_DEFAULT_URI=mongodb;MONGODB_HOST=localhost;MONGODB_PORT=27017;'
const objs = str.split(';').map(a=> {
    const divided = a.split('=');
    const obj = {};
    obj[divided[0]] = divided[1];
    return obj;
})

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 repair all the data or preserve it using my current theme?

Seeking assistance here. I am new to developing themes and have a query. Let's say, I have developed a theme myself. Now my question is, after creating menus, posts, pages, etc., when I install just the theme on another WordPress site, all the data ge ...

What is the process for obtaining a value when you click and then retrieving the associated ID?

I am looking to create a function that, when clicking on the square with the ID "colors", will return the sentence containing the colors from the table in PHP files with the ID "retours_couleurs". Apologies for any mistakes in my English, as I am French. ...

The getHours function seems to be malfunctioning when calculating the difference between dates

[code][1] Hello, I am currently working on calculating the difference between two dates and I want the result to be displayed in the format 00:00:00. Currently, my "current" time is set as 00:00:00 but I need it to dynamically update based on the hours, m ...

Retrieving data from a simulated angular service and making calls accordingly

I'm struggling with writing tests for a controller method that relies on an Angular service call and needs to test the code inside the .then() function afterwards. Here's the basic concept: // Controller $scope.myMethod = function() { meth ...

Ways to eliminate the index of the parent array from an array

Eliminating the parent array index within an array is my current objective. This is the array I am working with: Array ( [0] => Array ( [0] => Array ( [id] => 296 [u ...

Storing an array of objects with properties in a plist file for safekeeping

I have an array called bugs that contains different types of objects such as strings, UIImage, etc. These objects are sorted as shown below: Example: BugData *bug1 = [[BugData alloc]initWithTitle:@"Spider" rank:@"123" thumbImage:[UIImage imageNamed:@"1.j ...

Troubleshooting Google Analytics on Localhost: Investigating Issues with Test Code

I've been working on an HTML file and wanted to integrate Google Analytics into it. After signing up with GA, I received a tracking code to insert into my HTML file within the head section at the very beginning. I followed the instructions and then pr ...

Exploring the applications of the `this` keyword within a jQuery-based JavaScript object

Recently, there has been a challenge in creating a JavaScript object with the specific structure outlined below: function colorDiv(div){ this.div=div; this.div.bind("click",this.changeColor) this.changeColor(){ this.div.css(" ...

What is the best way to display numerous images on a cube face while also organizing them like a gallery wall?

I'm working on creating a unique gallery wall using three.js. Currently, I have successfully rendered an image on each side like this: My goal is to place multiple images on each wall instead of just one large image. Something similar to this concept ...

What is the correct way to set up Cypress intercepts within a beforeEach function?

As a newcomer to Cypress, I find some aspects of it challenging despite its apparent simplicity. I am facing a specific issue: const componentsRouteMatcher = { pathname: '/component-management/api/components', query: { size: &apos ...

What is the best way to change a Buffer array into hexadecimal format?

After making a call to one of my API endpoints, I am receiving a Buffer array in a JSON object. My goal is to convert this array into a more user-friendly format such as hex so that I can easily compare them. Below is a snippet of the current object struct ...

Issue encountered when attempting to connect an external script to a Vue single file component

Struggling to link an external script to a single file component in Vue. My project setup is as follows: https://i.sstatic.net/LWvNx.png I need to link the file components/Sshy to ../javascripts/ I have successfully linked other scripts using either of ...

Error in Node.js child_process: unable to access the property '_writableState' as it is undefined

I'm currently working on integrating ffmpeg's functionality into a Node.js API by utilizing the child_process library. However, I encounter an error when trying to pass data to ffmpeg's stdin pipe, specifically getting a TypeError: Cannot re ...

Identify the mouse's location in relation to its parent element, not the entire webpage

A script I've been working on detects the mouse position relative to the page, taking into account a movement threshold of 100px before triggering certain actions. // Keep track of last cursor positions var cursorDistance = 0; var lastCursorX = null; ...

A step-by-step guide on confirming reCAPTCHA during a server request

SITUATION: In the past, I used a simple form submit with POST to "/login" to check my recaptcha. For security reasons, I need to change my implementation and am considering the following steps: 1) Using jQuery to submit the form. 2) Making a call to th ...

"Upon loading an FBX file in Threejs, some model parts are not displayed

Hello, I am in need of assistance. I am currently working on importing FBX models into Threejs and here is the import code that I am using: let loader = new FBXLoader(); loader.load(model.obj_path, object => { let mix = new THREE.AnimationMixer(objec ...

Adding the tasksMap to the dependency array in the React useEffect hook will result in an endless loop

I'm facing an issue with adding tasksMap to the useEffect dependency array, as it causes an infinite loop. Can someone guide me on how to resolve this? To ensure that the user sees an updated view of tasks that are added or modified, I need the app to ...

Combining default and named exports in Rollup configuration

Currently, I am in the process of developing a Bluetooth library for Node.js which will be utilizing TypeScript and Rollup. My goal is to allow users to import components from my library in various ways. import Sblendid from "@sblendid/sblendid"; import S ...

Using Java to Work with Nested JSON Arrays

I am struggling to generate a json response that groups food items based on categories in Java. The desired output should resemble the following JSON structure: { "menu": { "items": [{ "id": 1, "code": "hot1_sub1_mnu", "name": "Mut ...

Having trouble displaying information in JavaScript after using getScript() to retrieve data from an API containing a JSON block database

I'm a newcomer to the world of Ajax/json/jquery and I find myself with a few inquiries. Currently, I am working with an API located at which contains a JSON block that looks something like this [{"id":"1","FirstName":"Micheal","LastName":"Kooling"}, ...