Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to affect an object with multiple keys for the same value

Tags:

javascript

I have some rules lookups that are based on state.. I am trying to think of a way to make accessing these easy without setting up some sort of intermediate step.

I'm imagining something like:

rules = {
  ['AK','FL','NY']: {a: 278},
  ['CA','LA','TX']: {a: 422}
}
console.log(rules['AK']); //278
console.log(rules['TX']); //422

I know that's not possible.. but wondering what the simplest way to achieve something like that would be

like image 456
Damon Avatar asked Oct 04 '15 05:10

Damon


People also ask

Can an object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can JavaScript object have multiple keys?

An object can have two same keys or two same values.

Can an object have multiple values?

Objects are Variables JavaScript variables can also contain many values. Objects are variables too. But objects can contain many values.


2 Answers

Take a page from MySQL's foreign key :

var states = {
   'AK' : 1,
   'FL' : 1,
   'NY' : 1,
   'CA' : 2,
   'LA' : 2,
   'TX' : 2
}

var rules = {
    1 : 278,
    2 : 422
}

Then you can reference the rules like so :

console.log(rules[states['AK']]);
like image 51
Anugerah Erlaut Avatar answered Oct 05 '22 13:10

Anugerah Erlaut


Affect Keys with same rule :

var rule1 = {a : 278}; 
var rule2 = {a : 422}; 

var rules = {
     'AK' : rule1, 
     'FL' : rule1, 
     'NY' : rule1, 
     'CA' : rule2, 
     'TX' : rule2
}; 

console.log(rules['AK']);   // {a:278}
console.log(rules['AK'].a); // 278

https://jsfiddle.net/sb5az0v5/

like image 34
Simone Nigro Avatar answered Oct 05 '22 13:10

Simone Nigro