简体   繁体   中英

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. The JSON is valid in the backend route, but when I get it in client-side, I get the object like above

Assuming that you get the json data which you can parse. You can use map method to create new objects having the new keys like this

 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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