0👍
I hope you are storing data in key: value
pairs Key will be item name and value will be the quantity in that case.
Before you push new entry, check the variable containing stored data whether a key in your case ‘state’ is already present. If present update value (‘payload’) alone. Else push both state and payload.
if ("key" in myObj)
{
//Code to update payload
}
else
{
//Code to insert key and value pair
}
or try this way
function keyExists(key, search) {
if (!search || (search.constructor !== Array && search.constructor !== Object)) {
return false;
}
for (var i = 0; i < search.length; i++) {
if (search[i] === key) {
return true;
}
}
return key in search;
}
// How to use it:
// Searching for keys in Arrays
console.log(keyExists('apple', ['apple', 'banana', 'orange'])); // true
console.log(keyExists('fruit', ['apple', 'banana', 'orange'])); // false
// Searching for keys in Objects
console.log(keyExists('age', {'name': 'Bill', 'age': 29 })); // true
console.log(keyExists('title', {'name': 'Jason', 'age': 29 })); // false
Optimized way to do the checking
yourObjName.hasOwnProperty(key) :
{
//Code to add payload alone
}
?
{
//Code to push state and payload;
}
- [Vuejs]-Dynamically Display Remotely Populated Dropdown in Vue.JS
- [Vuejs]-How to use this.$notification of Ant Design (Vuejs) in .js file?
Source:stackexchange.com