Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

split and convert a string into object

let data = "Child 1 First Name: Ali
Child 1 Gender: Female
Child 1 Hair Color: Blonde
Child 1 Hair Style: Wavy
Child 1 Skin Tone: Tan
Child 2 First Name: Morgan 
Child 2 Gender: Female
Child 2 Hair Color: Brown
Child 2 Hair Style: Ponytail
Child 2 Skin Tone: Light
Relationship 1 to 2: Brother
Relationship 2 to 1: Brother
";
//let data = JSON.stringify(rawNoteData);  <-- Don't do this. order.customer.note is not an object.

let foo = data.split("
").reduce(function(obj, str, index) {
  let strParts = str.split(":");
  if (strParts[0] && strParts[1]) { //<-- Make sure the key & value are not undefined
    obj[strParts[0].replace(/s+/g, '')] = strParts[1].trim(); //<-- Get rid of extra spaces at beginning of value strings
  }
  return obj;
}, {});

console.log(foo);
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #split #convert #string #object
ADD COMMENT
Topic
Name
9+1 =