Home > Net >  How to change field from return response in api
How to change field from return response in api

Time:07-07

This is the result of response from api

enter image description here

what I want is to change the field return like

_id to id

existing code

WorkflowApi.getTransactionLog().then(logs => {

  const newLog = {
      ...logs,
      'id': logs._id
  }

}

current result

enter image description here

CodePudding user response:

If you just want to change one specific item, you need to choose it by key - as they are numeric you'll have to use square bracket notation

WorkflowApi.getTransactionLog().then(logs => {

  const newLog = {
      ...logs[43],
      'id': logs[43]._id
  }

}

If you want to change all of them you'll need to loop

WorkflowApi.getTransactionLog().then(logs => {
  const newLogs = Object.fromEntries(Object.entries(logs).map( ([k,v]) =>  {
      return [k, {
          ...v,
          'id': v._id
      }]
  }))
}

For removing a key I would suggest something like this:

const objectWithoutKey = (object, key) => {
  const {[key]: deletedKey, ...otherKeys} = object;
  return otherKeys;
}

console.log(objectWithoutKey({_id:123,id:123},"_id"))

CodePudding user response:

Looks like the data is in array of objects. You need to map through array then add new field as id

   const newLog = logs.map(values => {
        return {
            ...values, id: values._id
        }
    })
  • Related