0

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."

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
J Seabolt
  • 2,576
  • 5
  • 25
  • 57

6 Answers6

3

The code below should work for your use case. Note that I've changed people to a mutable variable (not a const any more). Essentially all this does is iterate over each dictionary in your array, if it finds a dictionary with the "name" key it sets a "title" key with the same value and then deletes the "name" key.

var people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];

for (var i = 0; i < people.length; i++) {
  if (people[i].hasOwnProperty("name")) {
    people[i]["title"] = people[i]["name"];
    delete people[i]["name"];
  }
}

console.log(people);
abagshaw
  • 6,162
  • 4
  • 38
  • 76
3

You are very close, your if-condition is checking the value of your object rather than the key. So all you need to do is change:

if(arr[i][x] === 'name') // 'bob' === 'name' for {name: 'bob'}

to:

if(x === 'name') // 'name' === 'name' for {name: 'bob'}

Because the value of x in for(let x in arr[i]) is the key value that you are iterating.

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(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));
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
1
const people = [{age: 32},{name: 'bob'},{name: 'jack', age: 3}];

// Copy all properties.  If key is 'name' change it to 'title'
const copyObjectWithTitle = obj => 
  Object.keys(obj).reduce((objAcc, key) => {
    const value = obj[key];
    return Object.assign({}, objAcc, key === 'name' ? { title: value} : { [key]: value });
  }, {})

// Map over the list. If the object has the key 'name' return a copy with the key 'title' 
const nameToTitle = (list) => list.map(obj => obj.hasOwnProperty('name') ? copyObjectWithTitle(obj) : Object.assign({}, obj))

const updatedPeople = nameToTitle(people);  
adrice727
  • 1,482
  • 12
  • 17
1

you can map over the objects in the array and modify objects that have the name property as shown below

peoples.map(people => {
      if(people.hasOwnProperty('name')) {
        let title = people.name;
        delete people.name;
        return Object.assign({}, people, {title: title});
      }
      return people;
    })
0

I would do this, if you just want to change the name property to title:

function nameToTitle(objsArray){
  var s = objsArray.slice(), a; // make a copy
  for(var i in s){
    a = s[i];
    if(a.name){
      s[i].title = a.name; delete s[i].name;
    }
  }
  return s;
}
var objsArray = [{age:32},{name:'bob'},{name:'jack', age:3}];

console.log(nameToTitle(objsArray));
StackSlave
  • 10,613
  • 2
  • 18
  • 35
-1

This might get downvoted a bit, but just for fun :]

const people = [{age: 32}, {name: 'bob'}, {name: 'jack', age: 3}];

const result = eval(JSON.stringify(people).replace(/\bname\b/g, 'title'));

console.log(result);
Slai
  • 22,144
  • 5
  • 45
  • 53