2017-06-22 36 views
0

如何改變students[0] '約翰' 到的關鍵:暱稱改變鍵到另一個值的JavaScript

var students = []; 

    students.push({ Name: 'John', Track: 'HTML', Score: 2000 }); 

    students.push({ Name: 'Ron', Track: 'CSS', Score: 2400 }); 

    students.push({ Name: 'Jim', Track: 'javaScript', Score: 2800 }); 

因此,這將是這樣的:

{ NickName: 'John', Track: 'HTML', Score: 2000 } 
+0

'學生[0] = .NickName學生[0]請將.Name;刪除學生[0] .Name' –

回答

2
students[0].NickName = students[0].Name; 
delete students[0].Name; 
+1

@suresh得到OP沒有要求學生[0]不是所有的學生。 –

0

this thread解釋,簡單,非優化方式是:

students[0].NickName = students[0].Name; 
delete students[0].Name; 

但有更多的優化和巧妙的方法來做到這一點,我讓你在提到的線程中發現它們。

0

如果你想把它當作一個效用函數:

function convertNameToNickName(obj) { 
    obj.NickName = obj.Name; 
    delete obj.Name; 
} 

convertNameToNickName(students[0]); 
0

我想這個解決方案,它的工作!謝謝! :) obj.NickName = obj.Name; delete obj.Name;

+1

您是否重複[其他答案之一](https://stackoverflow.com/a/44695259)? – Pang

+1

這不是一個聊天或留言板!不要寫「謝謝」作爲答案,而應將其中一項工作答案標記爲已接受。 –

0
var students = []; 
students.push({ Name: 'John', Track: 'HTML', Score: 2000 }); 
students.push({ Name: 'Ron', Track: 'CSS', Score: 2400 }); 
students.push({ Name: 'Jim', Track: 'javaScript', Score: 2800 }); 
Object.prototype.renameProperty = function (oldName, newName) { 
    // Check for the old property name to avoid a ReferenceError in strict mode. 
    if (this.hasOwnProperty(oldName)) { 
     this[newName] = this[oldName]; 
     delete this[oldName]; 
    } 
    return this; 
}; 

students.forEach(function(ele) { 
    ele.renameProperty('Name','Nickname') 
}) 
console.log(students) 
2

避免使用delete。閱讀this

只需使用map

students = students.map(student => ({ 
    NickName: student.Name, 
    Track: student.Track, 
    Score: student.Score, 
})) 

或者用JS ES6 +

students.map(({ Name: NickName, ...student }) => ({ NickName, ...student })) 

只是一個指數

students = students.reduce((acc, curr, index) => { 
    if (index !== 0) 
     return curr 

    return ({ 
     NickName: curr.Name, 
     Track: curr.Track, 
     Score: curr.Score, 
    }) 
}, []) 
0

使用.map()我們就可以實現這一點很容易

var newArray = students.map((currentValue, index, array) => { 
    currentValue['NickName'] =currentValue['Name']; 
    delete currentValue['Name']; 
    return currentValue; 
}) 

console.log(newArray) 
相關問題