简体   繁体   English

在 JavaScript 中为对象的键添加引号和下划线

[英]Add quotes and underscores to keys of an object in JavaScript

I have an object with this shape :我有一个具有这种形状的对象:

{
IGG: "1007301297",
Date effet: "",
Statut deontologique: "B",
Version charte: "1",
N charte: "0",
Nom charte: "",
Statut charte: "A",
Date envoi charte: "",
Date 1ere relance: "",
Date 2eme relance: "",
Date 3eme relance: "",
Date de validation: "" 
}

but I want to replace all the spaces in keys by underscores and eventually add quotes like this :但我想用下划线替换键中的所有空格,并最终添加这样的引号:

{
"IGG": "1007301297",
"Date_effet": "",
"Statut_deontologique": "B",
"Version_charte": "1",
"N_charte": "0",
"Nom_charte": "",
"Statut_charte": "A",
"Date_envoi_charte": "",
"Date_1ere_relance": "",
"Date_2eme_relance": "",
"Date_3eme_relance": "",
"Date_de_validation": "" 
}

Is it possible ?是否可以 ?

Explanation : In fact I parse a csv datas to JSON with npm package csv-parser, and I send the JSON back to the client.说明:实际上,我使用 npm 包 csv-parser 将 csv 数据解析为 JSON,然后将 JSON 发送回客户端。 The JSON is valid in the backend route, but when I get it in client-side, I get the object like above JSON 在后端路由中是有效的,但是当我在客户端获取它时,我得到了上面的对象

Assuming that you get the json data which you can parse.假设您获得了可以解析的 json 数据。 You can use map method to create new objects having the new keys like this您可以使用 map 方法创建具有新键的新对象,如下所示

 var abc = { "IGG": "1007301297", "Date effet": "", "Statut deontologique": "B", "Version charte": "1", "N charte": "0", "Nom charte": "", "Statut charte": "A", "Date envoi charte": "", "Date 1ere relance": "", "Date 2eme relance": "", "Date 3eme relance": "", "Date de validation": "" } const keyValues = Object.keys(abc).map(key => { const newKey = key.replace(/\\s+/g, '_'); return { [newKey]: abc[key] }; }); console.log(keyValues)

obj1 = { "Foo Bar": "Baz"};
obj2 = {};
Object.keys(obj).forEach((key) => {obj2[key.replace(' ', '_')] = obj[key]});

You can do something like this!你可以做这样的事情!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM