Home > Software engineering >  How to slice the first object in the Array JS
How to slice the first object in the Array JS

Time:09-12

I have an array containing objects :

userFromDb [
  {
    _id: new ObjectId("62d54652982bed4574869188"),
    userName: 'adi',
    password: '1234'
  },
  {
    _id: new ObjectId("62d54747982bed457486919f"),
    userName: 'an',
    password: '12345'
  }
] 

I need to edit the _id in JS. This is the desired output:

userFromDb [
  {
    _id:'62d54652982bed4574869188',
    userName: 'adi',
    password: '1234'
  },
  {
    _id:'62d54747982bed457486919f',
    userName: 'an',
    password: '12345'
  }
]

I tried :

let userFromDb2 = userFromDb.map(x => x._id.slice(12))

And I got an error

TypeError: x._id.slice is not a function

Someone knows how to do it?

CodePudding user response:

You should specify the start and number of characters to cut in the string. so syntax let userFromDb2 = userFromDb.map(x => x._id.slice(0,12)) Hope this would help

CodePudding user response:

It really depends on structure of ObjectId class
for expample

class ObjectId {
    constructor(id) {
        this.id = id;
    }
}

in this class you can easily get id like this

let userFromDb2 = userFromDb.map(x => x._id.id)

and if you are using mongoDB this may help you this may help you

  • Related