javascriptobjectkey-valueelixir-jason

JS returing key : value pair as in JSON format


I am working on a problem where I'm supposed to get a two-word string from a JS object and transform it to two new key:value pairs (e.g. get from: {name: "Bob Jones", Age:34} to: {firstName:Bob, lastName:Jones, Age:34}).

Below my code:

/*enter original object, access value of "name" and split it in two; then create new object that will have a new property "last name" with the second part of original name value
    -code for finding where one part of strings end where the other begins, then output the part in separate properties*/

    function makeGuestList(person) {
    let oldName = person.name;
    let indexOfSpace = oldName.indexOf(" ");
    let givenName = oldName.slice(0,indexOfSpace);
    let familyName = oldName.slice(indexOfSpace);
    ///////////from here down something must be wrong
    person.firstName = givenName;
    person.lastName = familyName; //just update person
    delete person.name; //this was the original name property I need to get rid of
    
    //return person;
    console.log(person);
 }

I tried outputting in console and I think I know what's the issue. My object return as {"first Name":Bob, "lastName":Jones, Age:34} From what I found online (mainly here), this seems to be the JSON format, but the platform I'm doing the code on want's me to be able to output key/property of the object without quotes.

Any ideas, what can I be doing wrong? (I know there's probably a more efficient way of solving the issue than what I've done, I just want to understand the issue).

Sorry for being too verbose, and Thank you.


Solution

  • You still have typos in your edits. FYI, programming requires that you make zero typos. You will not be able to program like that. Please keep it in mind, and try to be careful.

    You wrote:

    My object return as {"first Name":Bob, "lastName":Jones, Age:34}

    What you meant might have been something like:

    My object returns as {"firstName":"Bob", "lastName":"Jones", "Age":34}

    Finally, here's how to print a JavaScript object, as JSON, without quotes:

    
    var myPersonObject = {"firstName":"Bob", "lastName":"Jones", "Age":34};
    
    var myPersonAsJSON = JSON.stringify( myPersonObject );
    
    //We will use a Regular Expression and the replace() function to remove the quotes:
    var myPersonAsJSONWithoutQuotes = myPersonAsJSON.replace( /"/g, "" );
    
    console.log( myPersonAsJSONWithoutQuotes );