如何使用Javascript动态替换JSON对象键中的空格? [英] How can I replace spaces in a JSON object keys dynamically using Javascript?
问题描述
如何动态地替换JSON对象键中的空格??例如,如果我有以下对象:
How can I replace the spaces in a JSON object's keys dynamically? For example, if I have the following object:
[{
"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"
}]
我希望能够将"FIRST NAME"和"LAST NAME"分别动态重命名为"FIRST_NAME"和"LAST_NAME".根据目前的研究,我具有以下功能:
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:
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;
}
传入的数据"参数是一个已经使用JSON.parse的对象,然后才进入此函数.
The "data" parameter being passed in is an object that has already had JSON.parse ran on it prior to entering this function.
我的这段代码的问题是,它很好地遍历了各个键,然后将适当的替换字符串分配给了"replacedKey",但没有将其分配给原始数据对象.
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.
推荐答案
此处是使用forEach
的完整代码.
Here's complete code using forEach
.
步骤与 Quentin 在其
严格从服务器以字符串形式获取JSON: 通过键中的 这篇关于如何使用Javascript动态替换JSON对象键中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!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>
_
替换空格.JSON.parse(jsonString.replace(/"([\w\s]+)":/g, function (m) {
return m.replace(/\s+/g, '_');
}));