【问题标题】:Add quotes and underscores to keys of an object in JavaScript在 JavaScript 中为对象的键添加引号和下划线
【发布时间】:2020-02-27 18:06:17
【问题描述】:

我有一个这种形状的物体:

{
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: "" 
}

但我想用下划线替换键中的所有空格并最终添加这样的引号:

{
"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": "" 
}

有可能吗?

说明:事实上,我使用 npm 包 csv-parser 将 csv 数据解析为 JSON,然后将 JSON 发送回客户端。 JSON 在后端路由中是有效的,但是当我在客户端获取它时,我会得到像上面这样的对象

【问题讨论】:

  • 你的对象无效,你是怎么定义的?
  • 事实上,我使用 npm 包 csv-parser 将 csv 数据解析为 JSON,然后将 JSON 发送回客户端。 JSON 在后端路由中是有效的,但是当我在客户端获取它时,我会得到像上面这样的对象

标签: javascript object key


【解决方案1】:
obj1 = { "Foo Bar": "Baz"};
obj2 = {};
Object.keys(obj).forEach((key) => {obj2[key.replace(' ', '_')] = obj[key]});

你可以这样做!

【讨论】:

    【解决方案2】:

    假设您获得了可以解析的 json 数据。您可以使用 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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多