Home > Back-end >  How to spread object inside object
How to spread object inside object

Time:05-19

I Have an object inside another object and I want to spread the inner one, my reason is when I want to call the object by it's id

My object

Resolver [
  { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_APPROVED_ONLINE' },
    count: 33
  },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_CANCELLED' },
    count: 1
  },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_UNKNOWN' },
    count: 1
  },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_DECLINED' },
    count: 15
  }
]

As shown above I want to append 'count' attribut inside '_id' attribute , i couldn't spread the inner one so How can I do it

CodePudding user response:

Code

const Resolver= [
  { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_APPROVED_ONLINE' },
    count: 33
  },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_CANCELLED' },
    count: 1
  },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_UNKNOWN' },
    count: 1
  },
  {
    _id: { _id: '05000002', totaloutcome: 'OUTCOME_DECLINED' },
    count: 15
  }
]

const result = Resolver.map(({_id, ...rest}) => {
  return { ..._id, ...rest };
});

console.log(result)

CodePudding user response:

You can do this using the spread operator:

array.map((item) => {
  return { ...item, ...item._id };
});
  • Related