如何更改students[0]
' John'发给:NickName
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 :(得分:2)
students[0].NickName = students[0].Name;
delete students[0].Name;
答案 1 :(得分: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,
})
}, [])
答案 2 :(得分:0)
正如this thread中所述,简单的非优化方式是:
students[0].NickName = students[0].Name;
delete students[0].Name;
但是有更多优化和聪明的方法来实现它,我让你在提到的线程中发现它们。
答案 3 :(得分:0)
如果你想把它当作效用函数:
function convertNameToNickName(obj) {
obj.NickName = obj.Name;
delete obj.Name;
}
convertNameToNickName(students[0]);
答案 4 :(得分:0)
我试过这个解决方案,它有效!谢谢! :) obj.NickName = obj.Name; 删除obj.Name;
答案 5 :(得分: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)
答案 6 :(得分:0)
使用.map()
我们可以轻松实现这一目标
var newArray = students.map((currentValue, index, array) => {
currentValue['NickName'] =currentValue['Name'];
delete currentValue['Name'];
return currentValue;
})
console.log(newArray)