1

I am trying to remove __v in every array element. How can I iterate through this array while removing the __v value from each element?

This is how my array looks like:

    [
    {
        "itemName": "SDGSGEDEDW",
        "description": "No description found",
        "_id": "5d97e155976e7e145476298b",
        "itemCode": "JFDQEKDEDQCGD",
        "untiPrice": 23.23,
        "vendor": "5d97e97177882e5b886fe32a",
        "dateAdded": "2019-10-05T00:18:29.128Z",
        "__v": 0 //want to remove this
    },
    {
        "itemName": "SDGSGEDEDW",
        "description": "No description found",
        "_id": "5d97e2e7d7a4b12dd800bca6",
        "itemCode": "JFDQEKDEDQCGD",
        "untiPrice": 23.23,
        "vendor": "5d97ea3177882e5b886fe330",
        "dateAdded": "2019-10-05T00:25:11.665Z",
        "__v": 0 //want to remove this
    }
]

So after removing the final array would should look like this:

[
    {
        "itemName": "SDGSGEDEDW",
        "description": "No description found",
        "_id": "5d97e155976e7e145476298b",
        "itemCode": "JFDQEKDEDQCGD",
        "untiPrice": 23.23,
        "vendor": "5d97e97177882e5b886fe32a",
        "dateAdded": "2019-10-05T00:18:29.128Z"
    },
    {
        "itemName": "SDGSGEDEDW",
        "description": "No description found",
        "_id": "5d97e2e7d7a4b12dd800bca6",
        "itemCode": "JFDQEKDEDQCGD",
        "untiPrice": 23.23,
        "vendor": "5d97ea3177882e5b886fe330",
        "dateAdded": "2019-10-05T00:25:11.665Z"
    }
]

Here what I was trying but it is not working:

arr.filter((item) => {
          return item.__v !== 0
});

How can I do this?

3 Answers3

1

Do that arr.forEach((item) => delete item.__v);

dev-cc
  • 434
  • 3
  • 13
0

This is how to do it

arr.forEach(function(item){
  delete item['__v'];
});

Also - if performance matters for your application - using a for loop would be better than forEach. Heres a bit more on why.

Pineapple Joe
  • 199
  • 10
0

You can use map and Destructuring assignment

const arr = [
    {
        "itemName": "SDGSGEDEDW",
        "description": "No description found",
        "_id": "5d97e155976e7e145476298b",
        "itemCode": "JFDQEKDEDQCGD",
        "untiPrice": 23.23,
        "vendor": "5d97e97177882e5b886fe32a",
        "dateAdded": "2019-10-05T00:18:29.128Z",
        "__v": 0 //want to remove this
    },
    {
        "itemName": "SDGSGEDEDW",
        "description": "No description found",
        "_id": "5d97e2e7d7a4b12dd800bca6",
        "itemCode": "JFDQEKDEDQCGD",
        "untiPrice": 23.23,
        "vendor": "5d97ea3177882e5b886fe330",
        "dateAdded": "2019-10-05T00:25:11.665Z",
        "__v": 0 //want to remove this
    }
];

const res = arr.map(item => {
  const { __v, ...rest} = item;
  return rest;
});

console.log(res);
zb22
  • 3,126
  • 3
  • 19
  • 34