3

I have an array of json objects.

var user =[ { id: 1, name: 'linto', img: 'car' },
  { id: 2, name: 'shinto', img: 'ball' },
  { id: 3, name: 'hany', img: 'kite' } ]

From this is want to remove attribute img from all the elements of the array, so the output looks like this.

var user =[ { id: 1, name: 'linto' },
  { id: 2, name: 'shinto' },
  { id: 3, name: 'hany' } ]

Is there a way to do this in java script.

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Haris Uddin
  • 85
  • 2
  • 8

2 Answers2

7

You can use .map() with Object Destructuring:

let data =[
  { id: 1, name: 'linto', img: 'car' },
  { id: 2, name: 'shinto', img: 'ball' },
  { id: 3, name: 'hany', img: 'kite' }
];
  
let result = data.map(({img, ...rest}) => rest);

console.log(result);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
4

Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

You can use map() in the following way:

var user =[ { id: 1, name: 'linto', img: 'car' },
  { id: 2, name: 'shinto', img: 'ball' },
  { id: 3, name: 'hany', img: 'kite' } ]
  
user = user.map(u => ({id: u.id, name: u.name}));
console.log(user);
Mamun
  • 66,969
  • 9
  • 47
  • 59