[removed] Object Rename Key

前端 未结 24 1389
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 00:18

Is there a clever (i.e. optimized) way to rename a key in a javascript object?

A non-optimized way would be:

o[ new_key ] = o[ old_key ];
delete o[ o         


        
24条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 01:16

    This is a small modification that I made to the function of pomber; To be able to take an Array of Objects instead of an object alone and also you can activate index. also the "Keys" can be assigned by an array

    function renameKeys(arrayObject, newKeys, index = false) {
        let newArray = [];
        arrayObject.forEach((obj,item)=>{
            const keyValues = Object.keys(obj).map((key,i) => {
                return {[newKeys[i] || key]:obj[key]}
            });
            let id = (index) ? {'ID':item} : {}; 
            newArray.push(Object.assign(id, ...keyValues));
        });
        return newArray;
    }
    

    test

    const obj = [{ a: "1", b: "2" }, { a: "5", b: "4" } ,{ a: "3", b: "0" }];
    const newKeys = ["A","C"];
    const renamedObj = renameKeys(obj, newKeys);
    console.log(renamedObj);
    

提交回复
热议问题