0

I have an Object like this

{ 
  "6":{  
    "id":2045,
    "categories":[  
      {  
         "id":7,
         "name":"Day Trips & Excursions Outside the City"
      },
      {  
         "id":2,
         "name":"Day-Tour"
      },
      {  
         "id":8,
         "name":"Food, Wine & Gastronomy"
      }
   ],
},
"8":{  
   "id":2045,
   "categories":[  
      {  
         "id":7,
         "name":"Day Trips & Excursions Outside the City"
      },
      {  
         "id":2,
         "name":"Day-Tour"
      },
      {  
         "id":8,
         "name":"Food, Wine & Gastronomy"
      }
   ],
  },
},

Now I just want to delete every object if its property(id) matches from a user supplied id

   [2045, 1234]

So in this case, I want to delete the object with id 2045 or 1234

 I tried multiple solution but failed, I just want to update the object something



   const categorytobedeleted = [2045, 12345];
   for(const v of categorytobedeleted) {
   const newobject = Object.values(oldobject).map(function(x) {
                  return x
              }).indexOf(v);
            Object.values(oldobject).slice(newobject, 1)
          }

     this.oldobject = this.newobject // maybe old object recreated with newly created object after deleting 

1 Answer 1

1

You can use reduce for this purpose:

const newObject = Object.keys(oldobject).reduce((a, oldKey) => {
    if (!categorytobedeleted.includes(oldobject[oldKey].id)) {
        a[oldKey] = oldobject[oldKey]
    }
    return a
}, {})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.