What is the proper way to send a List of Strings containing key=value pairs to an Object?

As a newcomer to JavaScript, I am seeking a more efficient method for converting a list string into an object.

The service provides me with the following list, but I require it in object form for processing purposes. For example:

 let objString = ['name=Antonio', 'phone=123-2312-3123', 'address=Paraiso'];

I aim to convert this list into an object like so:

    objString = { 
      'name': 'Antonio',
      'phone': '123-2312-3123',
      'address': 'Paraiso',
     }

Currently, I am unable to find a built-in JS method or simpler solution than using multiple loops for this conversion process.

Answer №1

Your unique string structure is highly specialized, so it doesn't have any built-in features for manipulation. The solution involves a single loop to parse the array and store key-value pairs in an object.

Instead of utilizing multiple loops

Simply utilize a single loop to iterate through the array elements and extract key-value pairs as shown below:

const objString = {}
const array = ['name=Antonio', 'phone=123-2312-3123', 'address=Paraiso']
array.forEach(el => {
    // Split the element at "="
    const parts = el.split('=')
    objString[parts[0]] = parts[1]
})
console.log(objString)

Answer №2

Transform the objString array into a key-value pairs by separating each string, then utilize Object.fromEntries() method to convert the array into an object:

const objString = ['name=Antonio', 'phone=123-2312-3123', 'address=Paraiso']

const result = Object.fromEntries(objString.map(str => str.split('=')))

console.log(result)

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

Merging sort and uniq functionalities to create a single function in JavaScript

I've been working with the sortBy and uniqBy functions, but I find myself iterating over the array twice when using the combined sortUniqBy. If you want to check out the code, feel free to click on this link to the codesandbox. Here's a snippet o ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. https://i.sstatic.net/MRsJ2.png ...

Encountering an 'Unexpected token u in JSON at position 0' error while utilizing the scan function in Amazon

I'm currently working on a Lambda function that is connected to an API. While most of the routes are functioning properly, I'm encountering an issue with the GET /items route which is supposed to retrieve all items from a DynamoDB table. Unfortun ...

What is the best location to integrate Swagger-UI in a Rails application using Grape?

I'm in the process of revamping a Rails application that heavily relies on APIs, utilizing Grape by Intridea and grape-swagger gem to incorporate Swagger UI for documentation. Currently, I have a basic hello world app up and running. It appears to be ...

Issue with Refresh Triggering Update, localStorage, useState, useEffect Combination

I want my app to execute the code inside the useEffect hook every 5 seconds, regardless of whether the page is refreshed or not. Currently, the code only runs when the page is refreshed and then remains inactive until the page is refreshed again. It seems ...

Utilize Express and Mongodb to interact with API and database queries

Looking for assistance with my project on creating a gaming server list. Users should be able to add their server by entering a title, IP, port, and some information about it. However, on the homepage, I also want to display the number of players and whet ...

Creating an array in C and populating it with the data from a text file

Having trouble with the code I wrote to read data from a text file and store it in an array. The code isn't opening the file as expected. The library headers being used are: #include <stdlib.h> #include <stdio.h> #include <string.h> ...

Is there a way to transform a Base64 image into a specific file type?

Is it possible to integrate my website with an iOS device and utilize the device's camera functionality? After capturing an image, the camera returns it in a base64 image format. Is there a way to convert this to a file type? If the mobile device pr ...

Leveraging the power of the Twitter API to integrate real-time tweets into custom code

Looking for an API that can transform a tweet from Twitter into a string format suitable for integration into a program or website. Any recommendations? ...

having difficulty reaching the globalProperties in vuejs v3

My latest project involves working with the Quasar framework in combination with vuejs 2 One of the key files in my project is located at /src/boot/gfunc.js import Vue from 'vue' Vue.prototype.$module = 'foo'; Within /quasar.conf.js ...

There seems to be an issue with the conversion of GLTF

Exploring the world of threejs in react has been quite an adventure for me. I discovered that the key to displaying 3D objects in react is by converting them into a JSX Component using gltfjsx. Following the procedure, I tried working with both glb and glt ...

Is it possible to access Firebase data in Vue.js, with or without Vuefire, using a router parameter before the DOM is rendered?

When I navigate to a view from another view, I pass the itemId as a param value to vue router. My goal is to call firebase with that itemId in order to filter the data and use the filtered result/data in the UI. Specifically, I am utilizing vuefire. The ...

"Encountering issues with ModalPopupExtender in Internet Explorer, while it functions properly in

Currently, I am encountering a critical issue while implementing ajaxmodalpopupextender on my webpage. The functionality operates smoothly in Firefox with an appealing appearance, however, it encounters display problems in IE where it appears to the side a ...

The this.setState method does not seem to be properly updating the nested array within the user object. However, when checking the same logic using console.log, the object

When the user selects multiple meals, they are stored in an array of objects inside the user object. Upon clicking submit, the code utilizes setState to update the user's meals as follows: submitAllMeals(arrayOfMeals) { this.setState({ u ...

Utilizing Symfony to store a JSON encoded file object within an entity

Trying to pass a file object to PHP and save it in the database with an AJAX call by following this approach: Javascript Code: e.preventDefault(); // get file object from input var image = $('#profilePictureInput').prop('files&apo ...

Sending POST request data to JSON in a Node.js environment

Below is a sample ajax-jQuery post request being sent: $('#postButton').click (function () { var empInfo = $('#empForm').serialize(); var empData = JSON.stringify(empInfo,null,2); $.ajax({ type: 'POS ...

When attempting to display an image from JSON data, it does not show up on my ListView item as expected

this is my json { contacts: [ { id: "c200", name: "Ravi Tamada", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e6c7f68775e79737f7772307d7173">[email protected]</a>", address: "xx-xx-xxxx,x - street, x - ...

Getting the dimensions of an image when clicking on a link

Trying to retrieve width and height of an image from this link. <a id="CloudThumb_id_1" class="cloud-zoom-gallery" rel="useZoom: 'zoom1', smallImage: 'http://www.example.com/598441_l2.jpg'" onclick="return theFunction();" href="http ...

Unlock the parent of an unnamed iframe

Here's a scenario: <div id="parent"> <iframe....></iframe> </div> If I had the above structure, I could use window.parent.document.getElementById('parent').innerHTML to access it. However, my current situation is di ...

Utilize Javascript to establish a fresh attribute by analyzing other attributes contained in an array within the object

Currently, I am working on a data structure that looks like this: masterObject: { Steps: [ { step: { required: false, }, step: { required: false, }, step: { required: false, }, }, ] } ...