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

Ways to iterate through a JSON formatted array variable using JavaScript

Below is my code snippet, used to plot all the locations fetched from my database onto a Google map. $.ajax({ url:"http://localhost/church_finder/index.php/MapController/search_church", type:'POST', data: ...

Use Go lang with Gin to return an empty array instead of null for JSON responses

I have a struct: type ProductConstructed struct { Name string `json:"Name"` BrandMedals []string `json:"BRAND_MEDALS"` } When I use gin to return my object: func constructProduct(c *gin.Context) { var response ProductConst ...

Troubleshooting problems with anchor-targets in Skrollr

I am experimenting with having divs overlap each other as the page is scrolled using Skrollr. Initially, I was able to achieve the desired effect with two divs. However, when trying to incorporate a third div, only the first and last ones seem to work prop ...

What is the best way to add randomness to the background colors of mapped elements?

I am looking for a way to randomly change the background color of each element However, when I try to implement it in the code below, the background color ends up being transparent: { modules.map((module, index) => ( <div className='carou ...

Automatically selecting and fetching checkbox values using JavaScript

I was struggling with coding a function that involved generating checkboxes using JavaScript. My goal is to automatically select the elements "March" and "September" from the array target[] and display them as checked in the text area. So, "March" and "Se ...

Animate the height transition of contenteditable after a line of text is added (using shift+enter) or removed

Currently, the contenteditable attribute is being utilized on the <div> tag to enable autogrow functionality similar to a textbox. Additionally, there is an attempt to incorporate a height transition. While most aspects are functioning correctly, the ...

Connect two radio buttons across separate forms

I am encountering an issue with two radio buttons that I am trying to link together. The problem arises because they are located in two separate form elements, causing them not to function as intended. It is important for the forms to be utilized in Bootst ...

Determine the total by multiplying the value of a dropdown menu and a text input field using jQuery when the values are changed

I am new to jQuery and JavaScript. I have a textbox and a select box, and when I enter a value in the textbox and select a value from the select box, I want to display the multiplication of both values in another textbox. I have tried doing this with two t ...

What is the command to invoke an asynchronous method from the node console?

I am working on a Bot class with an async printInfo method: class TradeBot { async printInfo() { //..... } } When I start 'node', and create an object from the console to call the method: >const createBot = require('./BotFactory&ap ...

Can you provide a guide on how to retrieve an HTML file using JSON?

There is a problem with fetching files in different formats. Specifically, I want to retrieve an HTML file that needs to be embedded in an iFrame. Currently, my AJAX request only retrieves SWF files. Is there a way to call and fetch the HTML file instead ...

What is the best way to determine the specific type of a value that is part of a union type?

Utilizing @azure/msal-react and @azure/msal-browser for implementing authentication in a React project with Typescript. The issue arises when TypeScript identifies event.payload as type EventPayload, but does not allow checking the exact type (e.g. Authen ...

The React router Link does not update the route after an if statement is executed

I'm in need of some assistance regarding React.js. Despite my efforts to find a solution, nothing has worked for me so far. Here are some examples of what I've searched for: How to use Redirect in the new react-router-dom of Reactjs Redirectin ...

Experience the Versatility of Android Mediaplayer Playing Local Files

I'm looking for guidance on how to play local audio/video files in Android Mediaplayer. I've managed to stream audio/video from URLs using a Variable storing the URL, but I'm unsure how to do it with local files. How can I utilize the localF ...

Enhance your SVG path by allowing users to drag points on Quadratic or Cubic Bezier curves

In my project, I am trying to make it so that when a user drags the point, it always stays aligned with the path. The goal is for the command Q, C, or S to adjust the curve based on the position of this draggable point, rather than treating it as a control ...

What is the method for conducting a partial data search in Node.js with MongoDB without explicitly specifying the field name?

After researching, I have found that the usual course of action is to specify field names. However, I am interested in achieving the same result without specifying any field name when saving JSON data into MongoDB and conducting partial searches. Is this ...

The notification panel pop-up box keeps moving away from the right side

I'm currently in the process of creating a straightforward vertical notification panel, similar to the one seen on Stack Overflow. However, I've encountered an issue where the pop-up is not staying positioned correctly to the right side. It behav ...

How to extract keys from an object using jQuery

I am currently working on implementing a Modal in bootstrap 5. I found a helpful guide at http://jsfiddle.net/341tfz8j/1/. I made the necessary changes to update the references from bootstrap 4 to bootstrap 5, such as changing data-toggle to data-bs-toggle ...

Is there a way to stop mUI from displaying the dropdown menu once Chrome automatically fills in a user's address details?

I am currently developing a form for users to enter their address in order to collect a billing address for payment information. Our services are only available to customers within the United States, so we have implemented an autocomplete UI component with ...

Preventing an RxJS Observable interval: A step-by-step guide

I am facing a unique scenario where I am using an RxJS interval, but I might need to abruptly stop it at any point. I thought there would be a simple method like cancel() or stop() similar to clearTimeout for intervals. Is there a way to stop an interval o ...

Updating state of an array nested inside an object using React and ES6

I'm fairly new to Javascript and I feel like my lack of fundamental knowledge might be hindering me from solving this issue. Despite trying different approaches and reading tutorials, I can't seem to get it right. My goal is to manipulate the st ...