问题
I want to remove single quotes from the array of objects in javascript.
var arr = ['{"email":"abc@gmail.com","name":"Abc"}',
'{"email":"def@hotmail.com","name":"Dr.Def"}',
'{"email":"xyz@gmail.com","name":"Xyz"}',
'{"email":"cad@hotmail.com","name":"Cat"}'];
I want output be like:
var arr=[{"email":"abc@gmail.com","name":"Abc"},
{"email":"def@hotmail.com","name":"Dr.Def"},
{"email":"xyz@gmail.com","name":"Xyz"},
{"email":"cad@hotmail.com","name":"Cat"}];
回答1:
You can use Array.prototype.map()
The
map()
method creates a new array with the results of calling a provided function on every element in the calling array.
and JSON.parse()
The
JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string.
var arr=[ '{"email":"abc@gmail.com","name":"Abc"}',
'{"email":"def@hotmail.com","name":"Dr.Def"}',
'{"email":"xyz@gmail.com","name":"Xyz"}',
'{"email":"cad@hotmail.com","name":"Cat"}'];
var res = arr.map(info => JSON.parse(info));
// Or simply
// var res = arr.map(JSON.parse);
console.log(res);
回答2:
JSON.parse the objects individually and store inside a new array and print it.
var arr=[ '{"email":"abc@gmail.com","name":"Abc"}',
'{"email":"def@hotmail.com","name":"Dr.Def"}',
'{"email":"xyz@gmail.com","name":"Xyz"}',
'{"email":"cad@hotmail.com","name":"Cat"}'];
var newarr=[];
arr.forEach((e)=>newarr.push(JSON.parse(e)))
console.log(newarr)
回答3:
var arr = ['{"email":"abc@gmail.com","name":"Abc"}',
'{"email":"def@hotmail.com","name":"Dr.Def"}',
'{"email":"xyz@gmail.com","name":"Xyz"}',
'{"email":"cad@hotmail.com","name":"Cat"}'];
let output = [];
for (let i = 0; i < arr.length; i++) {
output.push(JSON.parse(arr[i]));
}
console.log(output);
来源:https://stackoverflow.com/questions/54552242/how-to-remove-single-quote-from-array-of-objects-in-javascript