5

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.

0

2 Answers 2

8

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

5

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

4
  • can we add some kind of condition while doing the mapping? Like if we want to check Id is null or not.
    – Leo2304
    Commented Jan 20, 2021 at 10:37
  • 1
    @SouradeepBanerjee-AIS, map() is designed to iterate over all the array items and you can manipulate the items based on some condition. If you want to filter out some items then you can use filter():)
    – Mamun
    Commented Jan 20, 2021 at 12:06
  • 1
    Thanks, I used the filter function and was able to do it.
    – Leo2304
    Commented Jan 21, 2021 at 13:02
  • @SouradeepBanerjee-AIS, you are most welcome:)
    – Mamun
    Commented Jan 21, 2021 at 13:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.