0

How to change the key of students[0] 'John' to: 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 } );

So it will look like this:

{ NickName: 'John', Track: 'HTML', Score: 2000 }
Cœur
  • 37,241
  • 25
  • 195
  • 267

6 Answers6

2
students[0].NickName = students[0].Name;
delete students[0].Name;
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
xReeQz
  • 320
  • 1
  • 7
2

Avoid using delete. Read this

Simply use map

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

Or using JS ES6+

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

For just one index

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

    return ({
        NickName: curr.Name,
        Track: curr.Track,
        Score: curr.Score,
    })
}, [])
Guillaume L.
  • 61
  • 1
  • 3
0

As explained in this thread, the simple, non-optimized way is:

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

But there are more optimized and clever ways to do it, I let you discover them in the thread mentioned.

Derlin
  • 9,572
  • 2
  • 32
  • 53
0

If you want it as a utility function:

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

convertNameToNickName(students[0]);
Lennholm
  • 7,205
  • 1
  • 21
  • 30
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)
Mr.Pandya
  • 1,899
  • 1
  • 13
  • 24
0

using .map() we can achieve this easily

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

console.log(newArray)
Wesley Coetzee
  • 4,768
  • 3
  • 27
  • 45