0

I have the following string: Jack:13,Phil:15,Lucy:12I'm trying to fetch objects from this string.

This string would have 3 people objects with their ages. How can this be achieved?

I've tried the following:

var s = 'Jack:13,Phil:15,Lucy:12'

var obj1 = eval("("+s+")");
var obj2 = JSON.parse(s);

Logging any of the obj variables returns errors. Am I missing a simple trick here? Any explanation would be appreciated, thanks.

2
  • 5 answers yet no one explains how it works and why not use eval. That is what OP needs, besides simply posting the solution.. Commented Jun 15, 2018 at 9:21
  • @Adelin - I did start out saying something, then figured...meh. But you're right, I'll add it. Commented Jun 15, 2018 at 9:25

6 Answers 6

3

In general, if you're doing replaces on a string to turn it into something you can pass eval or JSON.parse, that's probably not your best approach. An in particular, avoid using eval (or its cousin new Function) when you can (you certainly can here), and always avoid eval (or its cousin new Function) with untrusted input.

A pair of splits with map does it:

const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
  .map(e => e.split(":"))
  .map(([name, age]) => ({name, age}));
console.log(people);

...or in ES5:

var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
  .map(function(e) { return e.split(":"); })
  .map(function(e) { return {name: e[0], age: e[1]}; });
console.log(people);

I'm not sure why I did two maps rather than just doing the second split and creating the object in the same callback; I guess I'm thinking more and more in a "functional programming" way. I'd change it, but Eddie's answer already does it in a single map, so...

...(edit) but since it looks like you wanted separate properties rather than using the person's name like Eddie did, here's an example of the above but with just a single map:

const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
  .map(e => {
    const [name, age] = e.split(":");
    return {name, age};
  });
console.log(people);

...or in ES5:

var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
  .map(function(e) {
    var parts = e.split(":");
    return {name: parts[0], age: parts[1]};
  });
console.log(people);

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

Comments

2

You can split() the string and use map() to loop thru the array. This will return an array of objects.

var s = 'Jack:13,Phil:15,Lucy:12';

var result = s.split(',').map(o => {
  let [k, v] = o.split(':');
  return {[k]: v};
});

console.log(result);


If you want a single object, you can use reduce

var s = 'Jack:13,Phil:15,Lucy:12';

var result = s.split(',').reduce((c, o) => {
  let [k, v] = o.split(':');
  return Object.assign(c, {[k]: v});
}, {});

console.log(result);

Comments

2

You can try with:

const result = s.split(',')
  .map(value => value.split(':'))
  .reduce((acc, [name, value]) => {
    acc[name] = +value;
    return acc;
  }, {});

Output:

{
  "Jack": 13,
  "Phil": 15,
  "Lucy": 12
}

Comments

2

As I'm sure you've worked out there are many ways to do this, I thought I'd add another method

let s = 'Jack:13,Phil:15,Lucy:12'
let obj = {};

s.split(",").forEach(part => {
  obj[part.split(":")[0]] = part.split(":")[1];
})
console.log(obj);

This is a simple split the string and then on each item of the new array do a split and push the results into an empty object already declared.

Comments

1

You could split the parts and build a new object with key/value pairs.

var string = 'Jack:13,Phil:15,Lucy:12',
    result = Object.assign(...string
        .split(',')
        .map(s => (([k, v]) => ({ [k]: v }))(s.split(':')))
    );
        
console.log(result);

For getting an array with objects

var string = 'Jack:13,Phil:15,Lucy:12',
    result = string
        .split(',')
        .map(s => (([name, age]) => ({ name, age }))(s.split(':')));
        
console.log(result);

Comments

1

Easy to do with .map():

var s = 'Jack:13,Phil:15,Lucy:12';
var items = s.split(',')
    .map((entry) => entry.split(':'))
    .map((item) => ({name: item[0], age: item[1]}));

console.log(items);

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.