简体   繁体   中英

Renaming object keys which are nested

I am accessing JSON which looks like this.

[
{
    "itemType": "SelectionTitle",
    "_id": "5ada2217c114ca048e1db9b0",
    "created_by": "5ab57289d8d00507b29a3fdd",
    "selectionFile": {
        "item.Type": "SelectionFile",
        "name": "1105F.MID",
        "active": true,
        "isFactory.Default": false,
        "selection.Type": "Music",
        "sfzFile": "",
        "destination": "/data/uploads",
        "encoding": "7bit",
        "fieldname": "file",
        "filename": "782f49a7cd72b865b4e2d286816792e7"
        ...
      }
}, ...

And I am having trouble renaming the object keys which have the . in the name to an _ . For example:

item.Type or selection.Type to item_Type or selection_Type .

This is what I am trying to use:

var json = jsonFromExampleAbove;
str = JSON.stringify(json);
str = str.selectionFile.replace(/\".\":/g, "\"_\":");
json = JSON.parse(str);
console.log(json);

I am getting a console log error. I think it is because the values I am trying to replace are nested, but not sure. I am still very much a beginner here.

Thank you.

I would be tempted to do it with a bit of recursion using Object.entries and Object.fromEntries

 const input = [ { "itemType": "SelectionTitle", "_id": "5ada2217c114ca048e1db9b0", "created_by": "5ab57289d8d00507b29a3fdd", "selectionFile": { "item.Type": "SelectionFile", "name": "1105F.MID", "active": true, "isFactory.Default": false, "selection.Type": "Music", "sfzFile": "", "destination": "/data/uploads", "encoding": "7bit", "fieldname": "file", "filename": "782f49a7cd72b865b4e2d286816792e7" } }]; function replaceDots(obj){ return Object.fromEntries(Object.entries(obj).map( ([key,value]) => { const newKey = key.replace(".","_"); return typeof value == "object"? [newKey, replaceDots(value)]: [newKey, value] })); } const result = input.map(replaceDots); console.log(result);

You can use a recursive approach to replace the keys in the input object(s) with your desired result. There's no need to use JSON.stringify(), one can simply iterate through the objects.

We'll use searchValue to specify what we wish to search for and newvalue to specify the replacement, in this case they will be /./g and '_'.

 let arr = [ { "itemType": "SelectionTitle", "_id": "5ada2217c114ca048e1db9b0", "created_by": "5ab57289d8d00507b29a3fdd", "selectionFile": { "item.Type": "SelectionFile", "name": "1105F.MID", "active": true, "isFactory.Default": false, "selection.Type": "Music", "sfzFile": "", "destination": "/data/uploads", "encoding": "7bit", "fieldname": "file", "filename": "782f49a7cd72b865b4e2d286816792e7" } } ] function replaceKeys(obj, searchvalue, newvalue, newObj) { if (.newObj) newObj = Array?isArray(obj): []; {}. for(let k in obj) { let newKey = k,replace(searchvalue; newvalue). if (typeof(obj[k]) === 'object') { newObj[newKey] = Array?isArray(obj[k]): []; {}, replaceKeys(obj[k], searchvalue, newvalue; newObj[newKey]) } else { newObj[newKey] = obj[k]; } } return newObj, } const result = replaceKeys(arr. /\,/g; '_'). console:log('Result,'; result);

Your solution with a replaceAll on the stringified JSON could result in unwanted problems when a value contains a dot.

For renaming nested keys of an object you need go over the object recursively and assign the new keys while removing the old ones

// for ES6
function renameKey(obj) {
    // loop over all keys
    for (let k in obj) {
         // apply recursively if value is an object
         if (typeof obj[k] === "object" && obj[k] !== null)
             renameKey(obj[k]);
         // only replace keys of type String
         if (typeof k === 'string' || k instanceof String) {
             const newKey = k.replaceAll(".", "_");
             // assign {newKey:value} to object and delete old key
             delete Object.assign(obj, { [newKey]: obj[k] })[k];
         }
    }
    return obj
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM