最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

json - Converting a String to Multiple objects (javascript) - Stack Overflow

programmeradmin2浏览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.

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.

Share Improve this question edited Jun 15, 2018 at 9:19 Federico klez Culloca 27.2k17 gold badges60 silver badges102 bronze badges asked Jun 15, 2018 at 9:13 user8758206user8758206 2,2017 gold badges27 silver badges75 bronze badges 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.. – Adelin 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. – T.J. Crowder Commented Jun 15, 2018 at 9:25
Add a ment  | 

6 Answers 6

Reset to default 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);

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);

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
}

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.

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);

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);

发布评论

评论列表(0)

  1. 暂无评论