How to remove single quote from array of objects in javascript

谁说胖子不能爱 提交于 2019-12-23 07:01:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!