Dean Jason
Dean Jason

Reputation: 105

Change object in array's key name

arr = [
    {"id":"1"},
    {"id":"2"}
];

For some reason I want to change the "id" to "uid". I am stuck here

arr.forEach(function(i){

});

Upvotes: 0

Views: 85

Answers (4)

Amadan
Amadan

Reputation: 198304

arr = [{
    "id": "1"
  },
  {
    "id": "2"
  }
];
arr.forEach(function(i) {
  i.uid = i.id;
  delete i.id;
});
console.log(arr);

This will modify arr. If you want a copy of arr that has the changed structure, follow Mritunjay's answer.

Upvotes: 2

C Nimmanant
C Nimmanant

Reputation: 7

arr = [{
    "id": "1"
  },
  {
    "id": "2"
  }
];
arr = arr.map(function(item, index) {
  // forget about the index, e.g. running from 0 to arr.length - 1
  return {
    uid: item.id
  };
});
console.log(arr);

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25882

Just do like bellow:

arr = [{
    "id": "1"
  },
  {
    "id": "2"
  }
];
arr = arr.map(function(obj) {
  return {
    "uid": obj.id
  }
});

console.log(arr);

Upvotes: 1

Downgoat
Downgoat

Reputation: 14361

Here you go:

arr.map(function (a) {
    a.uid=a.id;delete a.id;
    return a;
});

This just goes through the array, renames it, and returns the value.

Snippet:

var arr = [{
  "id": "1"
}, {
  "id": "2"
}];

arr = arr.map(function(a) {
  a['uid'] = a['id'];
  delete a['id'];
  return a;
});

console.log(arr);


You mentiond forEach so here's an answer with it.

arr.forEach(function (a) {
    a.uid=a.id;delete a.id;
});

Upvotes: 0

Related Questions