-1

So I have an array with 3 objects

categories:[
{
 id: '1',
 name: 'firstItem',
 description: 'firstDesc'
}
{
 id: '2',
 name: 'secondItem',
 description: 'secondDesc'
}
{
 id: '3',
 name: 'thirdItem',
 description: 'thirdDesc'
}
]

My question is, how can I filter this array to get the same array of 3 objects but without 'description' property?

Filippo854
  • 149
  • 9
  • Does this answer your question: https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object?rq=1 ? – Daniel Dec 09 '20 at 17:22
  • You want to `map`, not `filter`. And give it a function which takes an object and returns the same object with only `id` and `name` properties. – Robin Zigmond Dec 09 '20 at 17:23

4 Answers4

1

Use array.map to achieve this:

const array = [{
    id: '1',
    name: 'firstItem',
    description: 'firstDesc'
  },
  {
    id: '2',
    name: 'secondItem',
    description: 'secondDesc'
  },
  {
    id: '3',
    name: 'thirdItem',
    description: 'thirdDesc'
  }
];

const array1 = array.map(item => {
  const {
    description,
    ...rest
  } = item;
  return rest;
});

console.log(array1);
glinda93
  • 7,659
  • 5
  • 40
  • 78
1

Simple one-liner to mutate the original array:

let arr = [{id: '1',name: 'firstItem',description: 'firstDesc'},{id: '2',name: 'secondItem',description: 'secondDesc'},{id: '3',name: 'thirdItem',description: 'thirdDesc'}];

arr.forEach(e => delete e.description);

console.log(arr);
NullDev
  • 6,739
  • 4
  • 30
  • 54
0
let categories = [
{
 id: '1',
 name: 'firstItem',
 description: 'firstDesc'
}
{
 id: '2',
 name: 'secondItem',
 description: 'secondDesc'
}
{
 id: '3',
 name: 'thirdItem',
 description: 'thirdDesc'
}
];

let newCategories = categories.map(({ id, name }) => ({ id, name }))
Rubydesic
  • 3,386
  • 12
  • 27
0

You don't actually want to "filter" per say, as in depending on a condition removing elements from an array.

You want to map over your array and then for each object (item) composing this array you want to remove the description property

You can easily achieve this by using the .map method available for Arrays

The .map method works as follows (from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) :

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

// For each object, return a new one without the description property
const result = yourArray.map(obj => {
  const { name, description, id } = obj;
  return { name, id };
})
Oskar Grosser
  • 2,804
  • 1
  • 7
  • 18
MaieonBrix
  • 1,584
  • 2
  • 14
  • 25