我有一个字符串
string = "firstName:name1, lastName:last1";
现在我需要一个obj对象
obj = {firstName:name1, lastName:last1}
我怎样才能在JS中做到这一点?
答案 0 :(得分:148)
实际上,最好的解决方案是使用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();
答案 1 :(得分:59)
您的字符串看起来像没有花括号的JSON字符串。
这应该适用:
obj = eval('({' + str + '})');
答案 2 :(得分:46)
如果我理解正确:
var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
我假设属性名称位于冒号的左侧,而它所采用的字符串值位于右侧。
请注意Array.forEach
是JavaScript 1.6 - 您可能希望使用工具包以获得最大兼容性。
答案 3 :(得分:31)
这种简单的方法......
var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);
输出
name1
答案 4 :(得分:11)
如果你正在使用JQuery:
var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg
记住:eval是邪恶的! :d
答案 5 :(得分:7)
您需要使用JSON.parse()将String转换为Object:
var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');
答案 6 :(得分:4)
我在几行代码中实现了一个非常可靠的解决方案。
我想要传递自定义选项的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')));
答案 7 :(得分:3)
如果您有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文档:
演示:http://jsbin.com/hiduhijevu/edit?js,console
功能:
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!
答案 8 :(得分:2)
string = "firstName:name1, lastName:last1";
这将有效:
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split(':');
fieldObject[c[0]] = c[1];
});
}
但效率不高。当你有这样的事情时会发生什么:
string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";
split()
将拆分“http”。所以我建议你使用像管道一样的特殊分隔符
string = "firstName|name1, lastName|last1";
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split('|');
fieldObject[c[0]] = c[1];
});
}
答案 9 :(得分:1)
这是通用代码,无论你的输入有多长,但如果有以下内容都在相同的模式中:separator:)
var string = "firstName:name1, lastName:last1";
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
var b = i + 1, c = b/2, e = c.toString();
if(e.indexOf('.') != -1 ) {
empty[el] = arr[i+1];
}
});
console.log(empty)
答案 10 :(得分:1)
由于JSON.parse()方法要求将Object键括在引号中才能正常工作,因此,在调用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: Doe
即使字符串具有复杂的对象(如以下对象),此方法也将起作用,并且仍然可以正确转换。只要确保字符串本身用单引号引起来即可。
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 wars
答案 11 :(得分:1)
我正在使用JSON5,效果很好。
好的部分是它包含否 class Module(object):
def __init__(self):
self._backend = thnn_backend
self._parameters = OrderedDict()
self._buffers = OrderedDict()
self._backward_hooks = OrderedDict()
self._forward_hooks = OrderedDict()
self._forward_pre_hooks = OrderedDict()
self._modules = OrderedDict()
self.training = True
def named_modules(self, memo=None, prefix=''):
if memo is None:
memo = set()
if self not in memo:
memo.add(self)
yield prefix, self
for name, module in self._modules.items():
if module is None:
continue
submodule_prefix = prefix + ('.' if prefix else '') + name
for m in module.named_modules(memo, submodule_prefix):
yield m
和否 eval
,使用非常安全。
答案 12 :(得分:0)
在你的情况下
var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
KeyVal[i] = KeyVal[i].split(":");
obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}
答案 13 :(得分:0)
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”数组将包含所有对象
答案 14 :(得分:0)
我知道这是一篇过时的文章,但未找到该问题的正确答案。
var jsonStrig = '{';
var items = string.split(',');
for (var i = 0; i < items.length; i++) {
var current = items[i].split(':');
jsonStrig += '"' + current[0] + '":"' + current[1] + '",';
}
jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
jsonStrig += '}';
var obj = JSON.parse(jsonStrig);
console.log(obj.firstName, obj.lastName);
现在,您可以像使用对象一样正常使用obj.firstName
和obj.lastName
来获取值。
答案 15 :(得分:0)
首先,您需要在字符串的起点和终点连接{},假设条件是
yourString = "firstName:name1, lastName:last1";
您需要执行类似的操作
newString = "{"+"firstName:name1, lastName:last1"+"}" = "{firstName:name1, lastName:last1}"
现在有默认方法,可通过解析string将json字符串转换为json对象。 方法名称为 JSON.parse()。 现在执行类似的操作,将您的json字符串转换为json对象。
obj = JSON.parse(newString);
现在您可以在json对象中使用newString了。
答案 16 :(得分:0)
这是我处理某些边缘情况的方法,例如将空格和其他原始类型作为值
const str = " c:234 , d:sdfg ,e: true, f:null, g: undefined, h:name ";
const strToObj = str
.trim()
.split(",")
.reduce((acc, item) => {
const [key, val = ""] = item.trim().split(":");
let newVal = val.trim();
if (newVal == "null") {
newVal = null;
} else if (newVal == "undefined") {
newVal = void 0;
} else if (!Number.isNaN(Number(newVal))) {
newVal = Number(newVal);
}else if (newVal == "true" || newVal == "false") {
newVal = Boolean(newVal);
}
return { ...acc, [key.trim()]: newVal };
}, {});
答案 17 :(得分:0)
Object.fromEntries(str.split(',').map(i => i.split(':')));