Home > Software design >  If key value pair exists in Object then update it else add it in an object
If key value pair exists in Object then update it else add it in an object

Time:08-29

I have a blank object which I need to update on user action.

let userAction = {};

I have multiple buttons on page with unique ID's,

Like: Btn1, Btn2, whatever

So if as a user I will click Btn1 then my object should be updated with its id and number of click., Like this

userAction = {btn1: 1}

if I will click on bt2 then it would also update that object with its ID like this:

userAction = {btn1: 1, Btn2: 1 }

but if I will click any other button one more time then it should update the value by 1. Like this

So I click Btn1 again.. then object will look like this.

userAction = {btn1: 2, Btn2: 1 }

I tried to do it like this, just need to know is there any better or optimized option to do this.

let userAction  = {};

$('button').click(function(){
  let btnId = $(this).attr('id');
  let exisitngValue = userAction[`${btnId}`];
if (btnId in userAction){
  userAction[`${btnId}`] = exisitngValue 1;
}else {
userAction[`${btnId}`] = 1;
}
console.log(userAction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="Btn1">Button 1</button>  
<button id="Btn2">Button 2</button>  
<button id="Btn3">Button 3</button>  
<button id="whatever">whatever</button>

Is there any better way to do it?

CodePudding user response:

You could take just the id of the button directly without a template string and assign directly the value or zero and add one.

let userAction  = {};

$('button').click(function(){
  let btnId = $(this).attr('id');
  userAction[btnId] = (userAction[btnId] || 0)   1;
  console.log(userAction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="Btn1">Button 1</button>  
<button id="Btn2">Button 2</button>  
<button id="Btn3">Button 3</button>  
<button id="whatever">whatever</button>

CodePudding user response:

let userAction  = {};

$('button').click(function(){
  let btnId = $(this).attr('id');
  userAction[btnId]=userAction[btnId] ?  userAction[btnId] 1 : 1;
console.log(userAction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="Btn1">Button 1</button>  
<button id="Btn2">Button 2</button>  
<button id="Btn3">Button 3</button>  
<button id="whatever">whatever</button>

CodePudding user response:

let userAction  = {};

$('button').click(function(){
   let btnId = $(this).attr('id');
   userAction[btnId] = userAction[btnId] 1 || 1;

   console.log(userAction);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="Btn1">Button 1</button>  
<button id="Btn2">Button 2</button>  
<button id="Btn3">Button 3</button>  
<button id="whatever">whatever</button>

  • Related