Reputation: 347
I am working on a project using jQuery and KendoUI for jQuery, and I need to make a method for removing elements by updating it rather then actually mutating the object.
I have concluded that I should be using the spread syntax to identify and remove the object/option I receive as an argument, and then set my new list as the remaining objects/options.
I want to do something akin to this, but I'm slightly uncertain exactly how I can identify the object I want to remove without running a loop - and need advice on how to do this 'best practice'.
deleteOption: option => {
const { option, ...rest } = P.Order.Payment.get("paymentMethods");
P.Order.Payment.set("paymentMethods", rest);
}
My array consist of objects that are uniquely identified by a uid
-attribute.
Object in the array are created like this:
addNewCard: () => {
P.Order.Payment.addOption(
{
paymentName: "Kort",
type: "CC",
value: 0,
class: "form-control",
icon: "fal fa-credit-card",
validated: true,
uid: this.uid,
update: (values) => {
P.Order.Payment.updateOption(this, values);
},
rmItem: function(){
P.Order.Payment.subtractValue(this.uid);
P.Order.Payment.deleteOption(this);
}
}
);
},
SOLUTION:
The suggestions below ALMOST got me where I needed, but as the argument I recieve is an object, not a string I needed a string identifier to use them. As the object in my case always is part of an indexed array though I could use the index as my identifier, I also had to adjust my set method to correctly merge the remaining indexed array without affecting the associative part of the array holding Kendo functions.
deleteOption: option => {
const index = P.Order.Payment.get("paymentMethods").indexOf(option);
let { [index]: _, ...rest } = P.Order.Payment.get("paymentMethods");
rest = Array.from(rest).filter(entry => entry === undefined || null);
P.Order.Payment.set("paymentMethods", [ ...rest ]);
},
This solution solved my problem, I think it's fairly clean but it should have room for optimisation when used outside of KendoUI.
Upvotes: 0
Views: 81
Reputation: 44125
You need to use a computed property name:
deleteOption: option => {
const { [option]: option, ...rest } = P.Order.Payment.get("paymentMethods");
P.Order.Payment.set("paymentMethods", rest);
}
Upvotes: 1
Reputation: 386680
If you want to delete the key of the variable option
, you need a computed property with a dummy variable.
deleteOption: option => {
const { [option]:_, ...rest } = P.Order.Payment.get("paymentMethods");
P.Order.Payment.set("paymentMethods", rest);
}
Upvotes: 2