show the ways to remove an object in javascript with a conditional statement

You can try reduce function.

const amounts = { 
   "1": { "total_payment": 29, "frequency": 10, "amount": 500 },
   "4": { "total_payment": 27, "frequency": 1, "amount": 500 },
   "5": { "total_payment": 27, "frequency": 6, "amount": 483.33 },
   "6": { "total_payment": 28, "frequency": 10, "amount": 222.2 },
   "7": { "total_payment": 1, "frequency": 2, "amount": 1000 }
}

const modifiedAmounts = Object.keys(amounts).reduce((acc, cur) => {
      const {frequency, total_payment } = amounts[cur];
      if(frequency > total_payment) acc[cur] = amounts[cur];

      return acc;
}, {})

console.log(modifiedAmounts)

const modifiedAmounts = Object.keys(amounts).reduce((acc, cur) => {
      const {frequency, total_payment } = amounts[cur];
      if(frequency > total_payment) acc[cur] = amounts[cur];

      return acc;
}, {})

modifiedAmounts:

{
  "7": {
    "total_payment": 1,
    "frequency": 2,
    "amount": 1000
  }
}

if you would want the result in array obj, you can change the reduce function acc to be an array.

const amounts = { 
   "1": { "total_payment": 29, "frequency": 10, "amount": 500 },
   "4": { "total_payment": 27, "frequency": 1, "amount": 500 },
   "5": { "total_payment": 27, "frequency": 6, "amount": 483.33 },
   "6": { "total_payment": 28, "frequency": 10, "amount": 222.2 },
   "7": { "total_payment": 1, "frequency": 2, "amount": 1000 }
}

const modifiedAmounts = Object.keys(amounts).reduce((acc, cur) => {
      const {frequency, total_payment } = amounts[cur];
      if(frequency > total_payment) acc.push({[cur]: amounts[cur]});

      return acc;
}, [])

console.log(modifiedAmounts)

const modifiedAmounts = Object.keys(amounts).reduce((acc, cur) => {
      const {frequency, total_payment } = amounts[cur];
      if(frequency > total_payment) acc.push({[cur]: amounts[cur]});

      return acc;
}, [])

modifiedAmounts:

[
  {
    "7": {
      "total_payment": 1,
      "frequency": 2,
      "amount": 1000
    }
  }
]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top