javascript - Convert a string into a JSON object

Looking for assistance here as I am fairly new to this. My goal is to transform the fullName string returned from a webapp UI using Selenium WebDriverIO. Here's what I have:

const fullName = "Mr Jason Biggs";

The desired outcome should be structured like this:

title: 'Mr',
name: 'Jason',
surname: 'Biggs',

I attempted splitting the name, but unsure how to convert it into key-value pairs

const splitName = fullName.split(" ");
// Returns [ 'Mr', 'Jason', 'Biggs' ]

Answer №1

To separate a full name into its individual parts, you can simply create a new object and assign each part to its corresponding key:

const fullName = "Mr Jason Biggs";

const splitName = fullName.split(" "),
      person = { 
          title: splitName[0],
          name: splitName[1],
          surname: splitName[2]
      };
      
console.log(person);

If you have multiple strings that require this splitting process, you can abstract the code into a reusable function called getPersonObject. This function takes a string and returns an object with the split parts as keys:

function getPersonObject(str) {
    const splitName = str.split(" ");
    return {
        title: splitName[0],
        name: splitName[1],
        surname: splitName[2]
    };
}

const arrayOfNames = ["Mr Jason Biggs", "Dr Stephen Strange", "Ms Lilly Depp"];

console.log(arrayOfNames.map(getPersonObject));

Answer №2

If you're feeling creative and want to experiment with modern syntax, you can try implementing destructuring assignment too:

    const completeName = "Ms Taylor Swift";

    // Split the name and assign it to individual variables
    const [title, firstName, lastName] = completeName.split(' ');
    // Generate an object using shorthand property notation
    const person = {
      title,
      firstName,
      lastName
    };
    
    console.log(person);

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

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Storing Firestore Timestamp as a Map in the database

Snippet Below const start = new Date(this.date + 'T' + this.time); console.log(start); // Thu Sep 12 2019 04:00:00 GMT+0200 const tournament:Tournament = { start: firebase.firestore.Timestamp.fromDate(start) } When passing the tournament ...

Tips for minimizing object instantiation within a Java for loop

In my Java program, I am generating a JSON file with the following code: JSONObject json = new JSONObject(); JSONArray vertex = new JSONArray(); for (int i = 0; i < num; i++) { JSONObject usr1 = new JSONObject(); JSONObject usr2 = new JSONObjec ...

Obtaining data from a callback function within a NodeJS application

There is a function in my code that performs a backend call to retrieve an array of names. The function looks something like this: module.exports.getTxnList = function(index, callback) { ....some operations ..... .... callback(null, respon ...

“Unlocking the secret to extracting color from an image in React Native”

While it may sound like a silly question, I am new to the world of React technology. I am looking to extract colors from an image - for example, when a user selects an image to upload, I want to identify all the colors used in that image. If this is possib ...

Updating the div#content dynamically with Jquery without the need to refresh the page

After spending countless hours on this forum, I have yet to find a solution that perfectly fits my needs, so I will pose my question. Here is the gist of what I am attempting to accomplish: When the page loads, the default page fades in and displays. Wh ...

Sending request results to the client's browser in Node.js - A step-by-step guide

I am struggling with figuring out how to send the results of a 'request' to the client browser. This function is executed on my Node.js server. var request = require("request"); function RedirectReceiver(url, currentState, callback){ ; Send ...

Utilize the capabilities of the Dropbox Core API in Javascript to effortlessly transfer and store files on

I am currently developing a chrome-extension that has the ability to upload files to the user's Dropbox folder. I have implemented AJAX requests in my code to handle file uploads, and it is working fine for text-based file extensions such as .txt, .js ...

Storing a field of JSON object in Solr

I am a beginner with Solr and I am looking to index a JSON object that contains a field which is another JSON object. When I try to use the schema-less mode, I encounter this error: { "name": "BURGER KING", "phone": "+(1)-(403)-2153451", "ca ...

What is the best way to modify the views directory for deploying on Vercel?

Currently facing an issue trying to deploy my Express application with EJS template on Vercel. Post deployment, encountering an internal server error along with the following message in the logs: Error: Failed to lookup view "home.ejs" in views directory " ...

What is the best way to transform a JSON object from a remote source into an Array using JavaScript?

Attempting to transform the JSON object retrieved from my Icecast server into an array for easy access to current listener statistics to display in HTML. Below is the JavaScript code being used: const endpoint = 'http://stream.8k.nz:8000/status-json ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...

Only the initial AJAX request is successful, while subsequent requests fail to execute

I am facing an issue with multiple inputs, each requiring a separate AJAX request. < script type = "text/javascript" > $(document).ready(function() { $("#id_1").change(function() { var rating1 = $(this).v ...

Trouble with retrieving data from localStorage

On my webpage, I have set up multiple input fields where users can enter data. When they click a button, the data from these inputs is stored inside <span>...</span> elements (the intention being that the text remains visible in these <span& ...

How can I convert a list of Django model instances into JSON format?

I'm currently working on a view in my project: class ListUnseenFriendRequests(generics.GenericAPIView): permission_classes = (IsAuthenticated,) def get(self, request, format=None): friendship_requests_list = Friend.objects.unread_req ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

The script tags encountered an issue loading the resource with a status code of 404

Currently working on an ASP.NET MVC project and encountered an issue on one of the pages. Here is the code snippet with a script included at the bottom... @model IEnumerable<PixelBox.Dtos.ItemGetDto> @{ ViewBag.Title = "Index"; } <body> ...

The Nextjs Image was preloaded using link preload, but it remained unused after a short period following the window's load event

I've encountered an issue while working with Next.js, a React-based framework. I am attempting to display the logo.png image using the Image component provided by Next.js. My image is stored in this folder: public/img Here is the code I'm using ...