-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?

2
  • Does this answer your question: stackoverflow.com/questions/208105/… ? Commented Dec 9, 2020 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. Commented Dec 9, 2020 at 17:23

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Bro this question is answered alot of times.
Thank you :) that works for me ;)
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);

1 Comment

Thank you :) that also works for me ;)
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 }))

2 Comments

This is answered already alot of times.
Thank you :) that also works for me ;)
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 };
})

1 Comment

Thank you :) thats what I was looking for

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.