Home > database >  sorting data from array of objects and push data from its value in JavaScript
sorting data from array of objects and push data from its value in JavaScript

Time:11-03

I'm a beginner in javascript.

I have an some array of objects that looks like this:

[
  {
    id: 1,
    checkInStatus: 'pending',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 2,
    checkInStatus: 'success',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 3,
    checkInStatus: 'pending',
    overtimeStatus: 'success',
    checkOutStatus: 'success'
  }
]

And want to transform it into something like this:

[
  {
    id: 1,
    checkInStatus: 'pending'
  },
  {
    id: 1,
    overtimeStatus: 'pending'
  },
  {
    id: 2,
    overtimeStatus: 'pending'
   },
  {
    id: 3,
    checkInStatus: 'pending'
  }
]

I want to transform from the first data to the second data, how can this be achieved?

CodePudding user response:

You could try something like this:

const yourData = [
  {
    id: 1,
    checkInStatus: 'pending',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 2,
    checkInStatus: 'success',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 3,
    checkInStatus: 'pending',
    overtimeStatus: 'success',
    checkOutStatus: 'success'
  }
]

const pending = [];
for(const entry of yourData){
  for(const property in entry){
    if(entry[property] === 'pending'){
      pending.push({ id: entry.id, [property]: entry[property] });
    }
  }
}
console.log(pending); // Matches your output requirement

CodePudding user response:

let data = [
  {
    id: 1,
    checkInStatus: 'pending',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 2,
    checkInStatus: 'success',
    overtimeStatus: 'pending',
    checkOutStatus: 'success'
  },
  {
    id: 3,
    checkInStatus: 'pending',
    overtimeStatus: 'success',
    checkOutStatus: 'success'
  }
]

To find the array of objects whose overtimeStatus is pending, you typically loop over the array elements using a for loop and test if the value of the overtimeStatus satisfies the condition, like this:

let yourData = [];
for (let i = 0; i < data.length; i  ) {
    if (data[i].checkInStatus  === 'pending') {
        yourData.push(data[i]);
    }
}
console.log(yourData);
  • Related