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

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

arr.forEach(function(i){

});

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Just do like bellow:

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

console.log(arr);

1 Comment

This returns a new object in place of the old one, if OP decides to add more elements to the object, this won't work as properly without back and forth editing
0

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;
});

Comments

0

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);

2 Comments

nah.. lots of duplicate with others.. but fun anyways.
this is the exact same as Mritunjay's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.