175 javascript string object
我有一个字符串
string = "firstName:name1, lastName:last1";
Run Code Online (Sandbox Code Playgroud)
现在我需要一个对象obj这样
obj = {firstName:name1, lastName:last1}
Run Code Online (Sandbox Code Playgroud)
我怎么能在JS中这样做?
cod*_*nja 158
实际上,最好的解决方案是使用JSON:
JSON.parse(text[, reviver]);
1)
var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'
Run Code Online (Sandbox Code Playgroud)
2)
var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
Phi*_*ert 68
您的字符串看起来像没有花括号的JSON字符串.
这应该工作:
obj = eval('({' + str + '})');
Run Code Online (Sandbox Code Playgroud)
cdl*_*ary 49
如果我理解正确:
var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
Run Code Online (Sandbox Code Playgroud)
我假设属性名称在冒号的左侧,而它所采用的字符串值在右侧.
请注意,这Array.forEach是JavaScript 1.6 - 您可能希望使用工具包以获得最大兼容性.
小智 34
这个简单的方法......
var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);
Run Code Online (Sandbox Code Playgroud)
产量
name1
Run Code Online (Sandbox Code Playgroud)
Fai*_*hti 19
由于 JSON.parse() 方法需要将对象键括在引号内才能正常工作,因此在调用 JSON.parse() 方法之前,我们首先必须将字符串转换为 JSON 格式的字符串。
var obj = '{ firstName:"John", lastName:"Doe" }';
var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});
obj = JSON.parse(jsonStr); //converts to a regular object
console.log(obj.firstName); // expected output: John
console.log(obj.lastName); // expected output: DoeRun Code Online (Sandbox Code Playgroud)
即使字符串具有复杂对象(如下所示),这也会起作用,并且它仍然可以正确转换。只需确保字符串本身包含在单引号内。
var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"] }}';
var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {
return '"' + s.substring(0, s.length-1) + '":';
});
var obj = JSON.parse(jsonStr);
console.log(obj.favorites.movies[0]); // expected output: star warsRun Code Online (Sandbox Code Playgroud)
mza*_*zar 12
如果您使用的是JQuery:
var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg
Run Code Online (Sandbox Code Playgroud)
记住:eval是邪恶的!:d
小智 9
您需要使用JSON.parse()将String转换为Object:
var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');
Run Code Online (Sandbox Code Playgroud)
小智 8
Object.fromEntries(str.split(',').map(i => i.split(':')));
Run Code Online (Sandbox Code Playgroud)
如果您有类似的字符串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;
}, {});
Run Code Online (Sandbox Code Playgroud)
感谢#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)
Run Code Online (Sandbox Code Playgroud)
令人困惑的MDN文档:
演示: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!
Run Code Online (Sandbox Code Playgroud)
我用几行代码实现了一个非常可靠的解决方案。
有一个像这样的 HTML 元素,我想在其中传递自定义选项:
<div class="my-element"
data-options="background-color: #dadada; custom-key: custom-value;">
</div>
Run Code Online (Sandbox Code Playgroud)
一个函数解析自定义选项并返回一个对象以在某处使用它:
<div class="my-element"
data-options="background-color: #dadada; custom-key: custom-value;">
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
390068 次 |
| 最近记录: |