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.

Mohammad Usman's user avatar
Mohammad Usman
39.6k20 gold badges99 silver badges101 bronze badges
askedOct 6, 2018 at 4:24
Haris Uddin's user avatar
0

2 Answers2

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

answeredOct 6, 2018 at 4:26
Mohammad Usman's user avatar
Sign up to request clarification or add additional context in comments.

Comments

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

answeredOct 6, 2018 at 4:27
Mamun's user avatar

4 Comments

can we add some kind of condition while doing the mapping? Like if we want to check Id is null or not.
@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():)
Thanks, I used the filter function and was able to do it.
@SouradeepBanerjee-AIS, you are most welcome:)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.