admin管理员组

文章数量:1417406

Lets say we have 2 Javascript objects and an array:

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

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

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

I want to change the field names in rawData according to the mapping indicated by displayNames, the final result should be:

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

Thanks!

Lets say we have 2 Javascript objects and an array:

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

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

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

I want to change the field names in rawData according to the mapping indicated by displayNames, the final result should be:

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

Thanks!

Share Improve this question asked Apr 9, 2013 at 18:30 CGPCGP 3033 silver badges8 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 1

Iterate rawData to build the new data object and use displayNames as a lookup table for the new property names:

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

本文标签: How to change a JavaScript object39s field namesStack Overflow