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

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 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 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 use filter():)
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.