1

I would like to convert a string array like that:

const arr = [
  "name:Adam age:20 height:180cm",
  "name:Sally age:30 height:170cm",
  "name:Mike age:35 height:185cm",
  "name:David age:40 height:190cm"
];

to this array that includes object with keys and values like that below:

var obj = [
  {name:'Adam', age:20, height:'180cm'},
  {name:'Sally', age:30, height:'170cm'},
  {name:'Mike', age:35, height:'185cm'},
  {name:'David', age:40, height:'190cm'}
];

Thanks!

3
  • What did you try so far? Commented Dec 4, 2020 at 9:48
  • I tried some for loop to initilaize values and key after split the strings. And also I tried Object.assign Commented Dec 4, 2020 at 9:49
  • You should include what you tried in the question. Commented Dec 4, 2020 at 16:46

3 Answers 3

4

const arr = [
  "name:Adam age:20 height:180cm",
  "name:Sally age:30 height:170cm",
  "name:Mike age:35 height:185cm",
  "name:David age:40 height:190cm"
]

let result = arr.map(e => Object.fromEntries(e.split(' ').map(n=>n.split(":"))))

console.log(result)

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

2 Comments

This will work, unless there are spaces or colons : in the data, of course, but that's a validation issue. Best would be to avoid to serialize the data in this "format" from the begining.
That was more intended to OP, this answer is good for the problem asked :)
2

You could use array map and split method to get your result.

const arr = [
  'name:Adam age:20 height:180cm',
  'name:Sally age:30 height:170cm',
  'name:Mike age:35 height:185cm',
  'name:David age:40 height:190cm',
];

const ret = arr.map((x) => {
  const obj = {};
  const a = x.split(' ');
  a.forEach((y) => {
    const [key, value] = y.split(':');
    obj[key] = key === 'age' ? +value : value;
  });
  return obj;
});
console.log(ret);

Comments

1

Sorry for the bad naming as I did this in a hurry but something like this should help:

s = "name:Adam age:20 height:180cm";
a = s.split(" ");
c = a.map(item => {
    pair = item.split(":");
    key = "\"" + pair[0] + "\"";
    value = "\"" + pair[1] + "\"";
    return key + ":" + value;
});
s = c.join(",");
s = "{" + s + "}";
o = JSON.parse(s);
console.log(o)

At the end o should be the object you want.

2 Comments

I took the liberty of turning your code into an executable snippet. FYI, there is this "Snippet" button available for HTML / JS code. And welcome to Stack Overflow!
Thanks! I realized eventually that I can do that, when I saw that my answer is the only one that does not do that.

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.