如何使用Javascript动态替换JSON对象键中的空格?

时间:2022-11-23 08:59:08

How can I replace the spaces in a JSON object's keys dynamically? For example, if I have the following object:

如何动态替换JSON对象的键中的空格?例如,如果我有以下对象:

[{
    "FIRST NAME": "Philip",
    "LAST NAME": "Rivers",
    "NUMBER": "17",
    "GPA": "1.0",
    "OLD_FACTOR": "8",
    "NICENESS": "1"
}, {
    "FIRST NAME": "Peyton",
    "LAST NAME": "Manning",
    "NUMBER": "18",
    "GPA": "4.0",
    "OLD_FACTOR": "5000",
    "NICENESS": "5000"
}]

I want to be able to dynamically rename "FIRST NAME" and "LAST NAME" to "FIRST_NAME" and "LAST_NAME" respectively. Based on research so far, I have this function:

我希望能够分别动态地将“FIRST NAME”和“LAST NAME”重命名为“FIRST_NAME”和“LAST_NAME”。根据目前为止的研究,我有这个功能:

function replaceSpaces(data) {
    debugger;
    for (var i = 0; i < data.length; i++) {
        var obj = data[i];
        for (var key in obj) {
            var replacedKey = key.split(' ').join('_');
            data[i][obj] = replacedKey;
        }
    }

    return data;
}

The "data" parameter being passed in is an object that has already had JSON.parse ran on it prior to entering this function.

传入的“data”参数是在进入此函数之前已在其上运行JSON.parse的对象。

My issue with this code is that it's looping through the keys just fine, and assigning the proper replaced string to "replacedKey", but it's not assigning that to the original data object.

我对这段代码的问题在于它正好循环键,并将正确替换的字符串分配给“replacementKey”,但它没有将其分配给原始数据对象。

3 个解决方案

#1


3  

Here's complete code using forEach.

这是使用forEach的完整代码。

The steps are same as Quentin has stated in his answer

这些步骤与昆汀在他的回答中所说的相同

  1. Copy the value
  2. 复制值

  3. Remove the key-value from the object
  4. 从对象中删除键值

  5. Add new item with new value in the object
  6. 在对象中添加具有新值的新项目

var arr = [{
  "FIRST NAME": "Philip",
  "LAST NAME": "Rivers",
  "NUMBER": "17",
  "GPA": "1.0",
  "OLD_FACTOR": "8",
  "NICENESS": "1"
}, {
  "FIRST NAME": "Peyton",
  "LAST NAME": "Manning",
  "NUMBER": "18",
  "GPA": "4.0",
  "OLD_FACTOR": "5000",
  "NICENESS": "5000"
}];


// Iterate over array
arr.forEach(function(e, i) {
  // Iterate over the keys of object
  Object.keys(e).forEach(function(key) {
    
    // Copy the value
    var val = e[key],
      newKey = key.replace(/\s+/g, '_');
    
    // Remove key-value from object
    delete arr[i][key];

    // Add value with new key
    arr[i][newKey] = val;
  });
});

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>


Strictly if the JSON is get in the form of String from server:

严格来说,如果JSON是从服务器获取String的形式:

Replace the spaces by _ from the keys.

用键替换_中的空格。

JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) {
    return m.replace(/\s+/g, '_');
}));

#2


4  

You need to:

你需要:

  • Copy the value
  • 复制值

  • Delete the old property
  • 删除旧属性

  • Modify the correct object. (data[i][obj] will convert obj to a string and try to use it as a property name).
  • 修改正确的对象。 (data [i] [obj]会将obj转换为字符串并尝试将其用作属性名称)。

Such:

    for (var original_property in obj) {
        var new_property = original_property.split(' ').join('_');
        obj[new_property] = obj[original_property];
        delete obj[original_property]
    }

#3


0  

since it is JSON it is expected to come as string you could do it with a help of Regex.

由于它是JSON,因此可以在Regex的帮助下实现它。

var processedJson = yourJson.replace(/( +)(?=[(\w* *]*":)/g, "_");
var yourObj = JSON.parse(processedJson);

/( +)(?=[(\w* *]*":)/g will find all ocurances of within " ... ": which is a key on every JSON object.

/(+)(?= [(\ w * *] *“:)/ g将找到”...“内的所有ocurance:这是每个JSON对象上的一个键。

#1


3  

Here's complete code using forEach.

这是使用forEach的完整代码。

The steps are same as Quentin has stated in his answer

这些步骤与昆汀在他的回答中所说的相同

  1. Copy the value
  2. 复制值

  3. Remove the key-value from the object
  4. 从对象中删除键值

  5. Add new item with new value in the object
  6. 在对象中添加具有新值的新项目

var arr = [{
  "FIRST NAME": "Philip",
  "LAST NAME": "Rivers",
  "NUMBER": "17",
  "GPA": "1.0",
  "OLD_FACTOR": "8",
  "NICENESS": "1"
}, {
  "FIRST NAME": "Peyton",
  "LAST NAME": "Manning",
  "NUMBER": "18",
  "GPA": "4.0",
  "OLD_FACTOR": "5000",
  "NICENESS": "5000"
}];


// Iterate over array
arr.forEach(function(e, i) {
  // Iterate over the keys of object
  Object.keys(e).forEach(function(key) {
    
    // Copy the value
    var val = e[key],
      newKey = key.replace(/\s+/g, '_');
    
    // Remove key-value from object
    delete arr[i][key];

    // Add value with new key
    arr[i][newKey] = val;
  });
});

console.log(arr);
document.getElementById('result').innerHTML = JSON.stringify(arr, 0, 4);
<pre id="result"></pre>


Strictly if the JSON is get in the form of String from server:

严格来说,如果JSON是从服务器获取String的形式:

Replace the spaces by _ from the keys.

用键替换_中的空格。

JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) {
    return m.replace(/\s+/g, '_');
}));

#2


4  

You need to:

你需要:

  • Copy the value
  • 复制值

  • Delete the old property
  • 删除旧属性

  • Modify the correct object. (data[i][obj] will convert obj to a string and try to use it as a property name).
  • 修改正确的对象。 (data [i] [obj]会将obj转换为字符串并尝试将其用作属性名称)。

Such:

    for (var original_property in obj) {
        var new_property = original_property.split(' ').join('_');
        obj[new_property] = obj[original_property];
        delete obj[original_property]
    }

#3


0  

since it is JSON it is expected to come as string you could do it with a help of Regex.

由于它是JSON,因此可以在Regex的帮助下实现它。

var processedJson = yourJson.replace(/( +)(?=[(\w* *]*":)/g, "_");
var yourObj = JSON.parse(processedJson);

/( +)(?=[(\w* *]*":)/g will find all ocurances of within " ... ": which is a key on every JSON object.

/(+)(?= [(\ w * *] *“:)/ g将找到”...“内的所有ocurance:这是每个JSON对象上的一个键。