This question already has answers here:
How do I remove a property from a JavaScript object? (40 answers)
Loop through an array in JavaScript (46 answers)
Closed7 years ago.
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.
2 Answers2
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); Sign up to request clarification or add additional context in comments.
Comments
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
You can usemap() 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 Comments
Leo2304
can we add some kind of condition while doing the mapping? Like if we want to check Id is null or not.
Mamun
@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 usefilter():)Leo2304
Thanks, I used the filter function and was able to do it.
Mamun
@SouradeepBanerjee-AIS, you are most welcome:)
Explore related questions
See similar questions with these tags.


