如何更改JavaScript对象的字段名称?

时间:2013-04-09 18:30:01

标签: javascript object field

假设我们有2个Javascript对象和一个数组:

var rawData = {
    "dModel": "Deluxe",
    "sizeMB": 256,
};

var displayNames = {
    "dModel": "Device Model",
    "sizeMB": "Size(MB)"
};

var fieldNames = ["dModel", "sizeMB"];

我想根据displayNames指示的映射更改rawData中的字段名称,最终结果应为:

var data = {
    "Device Model": "Deluxe",
    "Size(MB)": 256,
};

谢谢!

2 个答案:

答案 0 :(得分:1)

迭代rawData以构建新的data对象,并使用displayNames作为新属性名称的查找表:

var data = {};
for (var p in rawData)
    data[displayNames[p]] = rawData[p];

答案 1 :(得分:0)

for (var oldKey in displayNames)
{
    var newKey = displayNames[oldKey];
    rawData[newKey] = rawData[oldKey];
    delete rawData[oldKey];
}