js對象替換鍵值名稱

 js對象替換鍵值名稱

將obj中的id和name字段替換分別替換成爲「@id」,「@name」spa

代碼以下:code

let obj = [{id:1,name:"張三"},{id:2,name:"李四"}].map(function (item) {
    return{
        "@id":item.id,
        "@name":item.name
    }
})

 

對於對象對象

let obj = {
    id:1,
    name:"張三",
    age:20,
    grade:{
        Math :90,
        English :80
    }
}

例如:替換obj中grade屬性,將Math替換Chinese,將English替換成Chemistryblog

完整代碼爲:
ip

let obj = {
    id:1,
    name:"張三",
    age:20,
    grade:{
        Math :90,
        English :80
    }
}

obj.grade["Chinese"] = obj.grade.Math;
obj.grade["Chemistry"] = obj.grade.English;
delete obj.grade.Math;
delete obj.grade.English;
console.log(obj);       //{ id: 1,name: '張三',age: 20,grade: { Chinese: 90, Chemistry: 80 } }
相關文章
相關標籤/搜索