我有一个字符串
string = "firstName:name1, lastName:last1";
现在我需要一个对象obj这样
obj = {firstName:name1, lastName:last1}
我怎么能在JS中这样做?
实际上,最好的解决方案是使用JSON:
文档
JSON.parse(text[, reviver]);
1)
var myobj = JSON.parse('{ "hello":"world" }'); alert(myobj.hello); // 'world'
2)
var myobj = JSON.parse(JSON.stringify({ hello: "world" }); alert(myobj.hello); // 'world'
3)将函数传递给JSON
var obj = { hello: "World", sayHello: (function() { console.log("I say Hello!"); }).toString() }; var myobj = JSON.parse(JSON.stringify(obj)); myobj.sayHello = new Function("return ("+myobj.sayHello+")")(); myobj.sayHello();
您的字符串看起来像没有花括号的JSON字符串.
这应该工作:
obj = eval('({' + str + '})');
如果我理解正确:
var properties = string.split(', '); var obj = {}; properties.forEach(function(property) { var tup = property.split(':'); obj[tup[0]] = tup[1]; });
我假设属性名称在冒号的左侧,而它所采用的字符串值在右侧.
请注意,这Array.forEach
是JavaScript 1.6 - 您可能希望使用工具包以获得最大兼容性.
这个简单的方法......
var string = "{firstName:'name1', lastName:'last1'}"; eval('var obj='+string); alert(obj.firstName);
产量
name1
如果您使用的是JQuery:
var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}'); console.log(obj.path); // will print /img/filename.jpg
记住:eval是邪恶的!:d
您需要使用JSON.parse()将String转换为Object:
var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');
如果您有类似的字符串foo: 1, bar: 2
,则可以使用以下命令将其转换为有效的obj:
str .split(',') .map(x => x.split(':').map(y => y.trim())) .reduce((a, x) => { a[x[0]] = x[1]; return a; }, {});
感谢#javascript中的niggler。
更新说明:
const obj = 'foo: 1, bar: 2' .split(',') // split into ['foo: 1', 'bar: 2'] .map(keyVal => { // go over each keyVal value in that array return keyVal .split(':') // split into ['foo', '1'] and on the next loop ['bar', '2'] .map(_ => _.trim()) // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this }) .reduce((accumulator, currentValue) => { // reduce() takes a func and a beginning object, we're making a fresh object accumulator[currentValue[0]] = currentValue[1] // accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it // since reduce() works like map() in the sense it iterates over an array, and it can be chained upon things like map(), // first time through it would say "okay accumulator, accumulate currentValue[0] (which is 'foo') = currentValue[1] (which is '1') // so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it // second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'} return accumulator }, {}) // when there are no more things in the array to iterate over, it returns the accumulated stuff console.log(obj)
令人困惑的MDN文档:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
演示:http://jsbin.com/hiduhijevu/edit?js,控制台
功能:
const str2obj = str => { return str .split(',') .map(keyVal => { return keyVal .split(':') .map(_ => _.trim()) }) .reduce((accumulator, currentValue) => { accumulator[currentValue[0]] = currentValue[1] return accumulator }, {}) } console.log(str2obj('foo: 1, bar: 2')) // see? works!