3

i have object of array like this:

var arr = [{id: 1, url: 'something'},{id: 2, url: 'something2'}];

i want output like this :

[{id:1}, {id:2}]

Thanks in advance

Umar Tariq
  • 1,191
  • 1
  • 13
  • 14

3 Answers3

5

Just use Array#map

const arr = [{id: 1, url: 'something'},{id: 2, url: 'something2'}];
const mapped = arr.map(({id}) => ({ id }));

console.log(mapped);

In simple form

const arr = [{id: 1, url: 'something'},{id: 2, url: 'something2'}];
const mapped = arr.map(item => { return { id: item.id };});

console.log(mapped);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
3

You should use map function to pluck specific key value from object array.

var new_arr= arr.map(function (value, index, array) {

   return {"id": value.id}; 

});
hu7sy
  • 983
  • 1
  • 13
  • 47
0

If you can modify the original array, just remove the attr url

var arr = [{id: 1, url: 'something'},{id: 2, url: 'something2'}];
arr.forEach(o => delete o.url);
console.log(arr)
Ele
  • 33,468
  • 7
  • 37
  • 75
  • @FedericoklezCulloca well, maybe that JSON was received from an API provider and the OP wants to clean up that object. – Ele Feb 27 '18 at 13:25
  • It still seems rather contrieved and un-idiomatic. I mean, is this honestly the first thing that popped into your head when you saw the question? Not trying to be dismissive, I sincerly want to know. – Federico klez Culloca Feb 27 '18 at 13:27
  • @FedericoklezCulloca it's a valid approach because we don't have the complete context. The OP only wants to remove that attr according to his/her question. – Ele Feb 27 '18 at 13:31