I want to write a function that takes an array of objects as an argument. If an object in the array contains the key "name," I want to change that key to "title." I then want to return an updated version of the array of objects with all of the keys changed.
This is my attempt at doing this. It's not doing what I want it to.
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];
function nameToTitle(arr){
let result = [];
for(let i = 0; i < arr.length; i++){
if(arr[i].name){
let newObj = {};
for(let x in arr[i]){
if(arr[i][x] === 'name'){
newObj['title'] = arr[i][x];
}
else {
newObj[x] = arr[i][x];
}
}
result.push(newObj);
}
else {
result.push(arr[i])
}
}
return result;
}
console.log(nameToTitle(people));
This above code returns this:
[ { age: 32 }, { name: 'bob' }, { name: 'jack', age: 3 } ]
=> undefined
It doesn't change the name key to "title."