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 }
1
  • students[0].NickName = students[0].Name; delete students[0].Name Commented Jun 22, 2017 at 9:14

6 Answers 6

2
students[0].NickName = students[0].Name;
delete students[0].Name;
Sign up to request clarification or add additional context in comments.

1 Comment

@suresh atta the OP did ask for students[0] not for all students.
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,
    })
}, [])

Comments

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.

Comments

0

If you want it as a utility function:

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

convertNameToNickName(students[0]);

Comments

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)

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.