简体   繁体   English

删除数组中键周围的双引号

[英]Removing double-quotes around Keys in Array

my array has keys with double-quotes "" around them, how can I remove them?我的数组周围有带有双引号“”的键,我该如何删除它们?

I'm generating my object from input fields like this:我正在从这样的输入字段生成我的 object:

var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
var jsonStringObj = {
    users: [JSON.stringify(obj)]
};
console.log(jsonStringObj)

Result is like this:结果是这样的:

users: ["{"Firstname":"","Lastname":""}"] <<-- wrong

Expected array:预期数组:

users: [{Firstname:"john",Lastname:"doe"}] <<-- I want this

I have tried the following unsuccessful attempts:我尝试了以下不成功的尝试:

var string = JSON.stringify(array);
string.replace (/"/g,'');

When you write JSON.stringify to convert it in the string, it would add the double quotes to your keys.当您编写 JSON.stringify 以将其转换为字符串时,它会将双引号添加到您的键中。

You just have to write obj directly, it would behave as the normal object and not string.您只需直接编写obj ,它的行为就像正常的 object 而不是字符串。

So please update your code of lines with the below code.因此,请使用以下代码更新您的行代码。 It should resolve your problem.它应该可以解决您的问题。

var obj = {};
 obj.Firstname = document.getElementById("firstName").value;
 obj.Lastname = document.getElementById("surname").value;
 var jsonStringObj = {users: [obj]};
 console.log(jsonStringObj)

You can use JSON.parse(),this will change a json to object.您可以使用 JSON.parse(),这会将 json 更改为 object。 here is the example:这是示例:

var obj = JSON.parse(users)

if you want to change an object to string you use JSON.stringify(obj)如果要将 object 更改为字符串,请使用 JSON.stringify(obj)

There is no need to stringify the object at all.根本不需要对 object 进行字符串化。

 var obj = {}; obj.Firstname = ""; obj.Lastname = ""; var obj2 = {users: [obj]}; console.log(obj2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从键上的json_encoded字符串中删除双引号 - Remove double-quotes from a json_encoded string on the keys Javascript生成的字符串问题中的双引号 - Double-quotes in a Javascript generated string issue 正则表达式在 JavaScript 中的键周围添加双引号 - Regular Expression to add double quotes around keys in JavaScript 正则表达式在javascript中的值和键周围添加双引号 - regular expression add double quotes around values and keys in javascript 使用util.format,在数组中的每个字符串周围用双引号引起来 - Using util.format, double quotes around each string in an array 使用 javascript 从数组中删除方括号、双引号 - removing square brackets, double quotes from array using javascript 删除特定子字符串周围的引号 - Removing quotes around specific substrings 重新发布-JavaScrpt 拆分行正则表达式-“双引号”内的“双引号” - Repost - JavaScrpt split line Regex - 'double quote' inside 'double-quotes' 从Applescript发送HTML到Javascript时,如何正确转义双引号? - How do I properly escape double-quotes when sending HTML from Applescript into Javascript? 如何使用 angular 或 JQuery 删除来自本地存储的前导和尾随双引号 - How to remove leading and trailing double-quotes coming from local storage using angular or JQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM