Home > database >  How to loop in object of array with filed name and delete by price?
How to loop in object of array with filed name and delete by price?

Time:09-16

Have a object , and i need to delete object in month by price

my way (wrong):

const newArr = {
  month: [
    { count: 1, price: 10, _id: '65434684e7c9298236522446' },
    { count: 2, price: 20, _id: '463239a84e7c929345tqgr46' },
  ],
  year: [{}],
  weak: [{}],
  day: [{}],
}

Object.entries(currentPrices).map(([key, value]) => ({
   [key]: value.filter((dateItem) => dateItem.price !== price),
}))

CodePudding user response:

This is what you need to do. You have an error on your variable usages. You never mention what the variable currentPrices is. So check this below:

const newArr = {
    month: [{
            count: 1,
            price: 10,
            _id: '65434684e7c9298236522446'
        },
        {
            count: 2,
            price: 20,
            _id: '463239a84e7c929345tqgr46'
        },
    ],
    year: [{}],
    weak: [{}],
    day: [{}],
};

let price; // assign the variable price a value

if (newArr && newArr.month) {
    newArr.month = newArr.month.filter((dateItem) => dateItem.price !== price);
}

console.log(newArr);

CodePudding user response:

A quick solution is to filter the objects under month array to get those that have a price different than the price you want to delete and then assign the result back to the month array.

You may create a function that receives the price you want to be removed from the array that filters the items assigns the result to the month array.

The built-in Array.prototype.filter can come in handy in this situation.

Here's a live demo:

const obj = {
    month: [{
        count: 1,
        price: 10,
        _id: '65434684e7c9298236522446'
      },
      {
        count: 2,
        price: 20,
        _id: '463239a84e7c929345tqgr46'
      },
    ],
    year: [{}],
    weak: [{}],
    day: [{}],
  },
  /** this function filters the items that have a price equal to the supplied price in the "price" argument */
  deleteByPrice = price => obj.month = obj.month.filter(el => el.price != price);

/** remove items having price equals to 10 */
deleteByPrice(10);

/** print the object after removing the items */
console.log(obj)

Learn more about the filter method on MDN.

  • Related