我有一个字符串as
string = "firstName:name1, lastName:last1";
现在我需要一个对象obj这样
obj = {firstName:name1, lastName:last1}
我如何在JS中做到这一点?
我有一个字符串as
string = "firstName:name1, lastName:last1";
现在我需要一个对象obj这样
obj = {firstName:name1, lastName:last1}
我如何在JS中做到这一点?
当前回答
我在几行代码中实现了一个相当可靠的解决方案。
有一个像这样的HTML元素,我想传递自定义选项:
<div class="my-element"
data-options="background-color: #dadada; custom-key: custom-value;">
</div>
函数解析自定义选项并返回一个对象以在某处使用:
function readCustomOptions($elem){
var i, len, option, options, optionsObject = {};
options = $elem.data('options');
options = (options || '').replace(/\s/g,'').split(';');
for (i = 0, len = options.length - 1; i < len; i++){
option = options[i].split(':');
optionsObject[option[0]] = option[1];
}
return optionsObject;
}
console.log(readCustomOptions($('.my-element')));
其他回答
由于JSON.parse()方法需要将对象键括在引号中才能正确工作,因此在调用JSON.parse()方法之前,我们首先必须将字符串转换为JSON格式的字符串。
var obj = '{firstName:"John", lastName:"Doe"}'; var jsonStr = obj.replace(/(\w+:)|(\w+:)/g,函数(匹配str) { 返回' ' ' + matchedStr。substring (0, matchedStr。长度- 1)+ '":'; }); obj = JSON.parse(jsonStr);//转换为常规对象 console.log (obj.firstName);//期望输出:John console.log (obj.lastName);//期望输出:Doe
即使字符串有一个复杂的对象(如下所示),这也可以工作,并且仍然可以正确地转换。只要确保字符串本身是用单引号括起来的。
var strorobj = '{名字:"John Doe",年龄:33岁,最爱:{体育:["篮球","棒球"],电影:["星球大战","出租车司机"]}}'; var jsonStr = strObj.replace (/ (\ w +:) | (\ w +:) / g函数(s) { 返回' ' ' + s.substring(0, s.length-1) + ' ' ':'; }); var obj = JSON.parse(jsonStr); console.log (obj.favorites.movies [0]);//期望输出:Star Wars . //
我使用的是JSON5,它工作得非常好。
好的部分是它不包含eval和new Function,使用起来非常安全。
如果你有一个像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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/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!
我在几行代码中实现了一个相当可靠的解决方案。
有一个像这样的HTML元素,我想传递自定义选项:
<div class="my-element"
data-options="background-color: #dadada; custom-key: custom-value;">
</div>
函数解析自定义选项并返回一个对象以在某处使用:
function readCustomOptions($elem){
var i, len, option, options, optionsObject = {};
options = $elem.data('options');
options = (options || '').replace(/\s/g,'').split(';');
for (i = 0, len = options.length - 1; i < len; i++){
option = options[i].split(':');
optionsObject[option[0]] = option[1];
}
return optionsObject;
}
console.log(readCustomOptions($('.my-element')));
var stringExample = "firstName:name1, lastName:last1 | firstName:name2, lastName:last2";
var initial_arr_objects = stringExample.split("|");
var objects =[];
initial_arr_objects.map((e) => {
var string = e;
var fields = string.split(','),fieldObject = {};
if( typeof fields === 'object') {
fields.forEach(function(field) {
var c = field.split(':');
fieldObject[c[0]] = c[1]; //use parseInt if integer wanted
});
}
console.log(fieldObject)
objects.push(fieldObject);
});
"objects"数组将包含所有对象