0

How do i convert the following string input name: xyz friend: abc mobile: 123 into an array separating it as something like this [{key:"name", value:"xyz"}]

I have tried this code for splitting

let friend1 = 
'name:xyz 
friend:abc 
mobile_no:123'
let Array=friend1.split(" ");
console.log(Array)`

need help with the key and value part.

1
  • Why don't you use a proper data structure like JSON instead? Commented Jun 18, 2018 at 6:21

2 Answers 2

1

Try this:

  1. To remove colliding colon + whitespace pairs :, I replace them with ####
  2. Then split the array on the rest of whitespaces
  3. For each split, being in this case name####xyz, friend####abc and mobile####123, split them on #### and construct desired object

let string = "name: xyz friend: abc mobile: 123";
let array  = string
  .replace(/:\s/g, '####')
  .split(' ')
  .map(pair => {

    let split = pair.split('####');
    return { key: split[0], value: split[1] };

  });
  
console.log(array)

Sign up to request clarification or add additional context in comments.

5 Comments

But you don't have to make it that easy. How would you break JSON.parse?
Define "break". In that case, for me, JSON.parse("name: xyz friend: abc mobile: 123") is "broken". Nvm. I can only assume it is going to be used to parse some chunks of data stored locally, and not in production code. And as you can see, it helped.
Passing invalid inputs to a function which then by specification fails to parse it is not the same as breaking it. Breaking in this context means that with a given input, the function produces something that was not specified. e.g. name: x y.
Thanks a lot! was struggling with this for a whole day.
Was trying to solve this for a brief period.. Nice job!
1

If the input itself is an array, then this will do the object(dictionary) conversion

var targetDictionary = {};
var string = ["name: xyz", "friend: abc", "mobile: 123"];
for (var i = 0; i < string.length; i++) {
    var split = string[i].split(':');
    targetDictionary[split[0]] = split[1];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.