如何从JavaScript中的对象数组中删除单引号

时间:2019-02-06 11:11:45

标签: javascript arrays object single-quotes

我想从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"}'];

我希望输出如下:

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"}];

4 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.map()

  

map()方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数。

JSON.parse()

  

JSON.parse()方法解析一个JSON字符串,构造该字符串描述的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"}'];

var res = arr.map(info => JSON.parse(info));
// Or simply
// var res = arr.map(JSON.parse);
console.log(res);

答案 1 :(得分:0)

JSON。分别解析对象并将其存储在新数组中并进行打印。

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)
  

答案 2 :(得分:0)

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);

答案 3 :(得分:-1)

// Try this code by the "for in loop" method.

let 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 newArr = [];
for (const item in arr)
{
    newArr.push(JSON.parse(arr[item]))
} 
console.log(newArr)