0

I want to skip/remove an element from array object to display required data only and skip _id One answer is here but needs more detail

How to remove specific key and value from array object in javascript?

[
    {
        _id:"1",
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    },
    {
        _id:"2",
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    }
]

As you can see above the array object has three element, _id, id and title.

I want to achieve this result

[
    {
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    },
    {
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    }
]

I do not want to have _id I shall be very thankful

ZiaUllahZia
  • 1,072
  • 2
  • 16
  • 30

3 Answers3

1

You can use map() over array and remove the prop you want.

I have create a function removeProp() which will remove the any given prop from any array of objects.

const arr = [{
    _id: "1",
    id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
    title:"Work"
},{
    _id: "2",
    id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
    title:"Work"
}]

const removeProp = (arr, prop)=> arr.map(({[prop]:p, ...other}) => other);
console.log(removeProp(arr, "_id"))
glinda93
  • 7,659
  • 5
  • 40
  • 78
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can use Object.keys in conjunction w/ Array.prototype.reduce & object spreading to achieve this

const array = [
    {
        _id:"1",
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    },
    {
        _id:"2",
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    }
]

const createCompactArray = (array, keyToOmit) => array.map(o => Object.keys(o).reduce((o1, k) => (k!==keyToOmit?{ ...o1, [k]: o[k] }:o1), {}))

createCompactArray(array, '_id') // =>

[
    {
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    },
    {
        id:"d8a67aa5-10bd-43bb-be33-5e4219cedaf4",
        title:"Work"
    }
]

One of the benefits to this approach (having a re-usable function w/ a dynamic key to omit) is that you can use the same approach regardless of what key you want to omit.

You can even enhance this to accept multiple keys!

const createCompactArrayV2 = (array, keysToOmit = []) => array.map(o => Object.keys(o).reduce((o1, k) => (!keysToOmit.includes(k)?{ ...o1, [k]: o[k] }:o1), {}))
james_womack
  • 10,028
  • 6
  • 55
  • 74
-1

You can just delete the _id field.

arr.forEach((item) => {delete item._id})
devastro
  • 79
  • 3