Reputation: 391
I have the following javascript object that represents columns of a table that I want user can select to show and analyze based on his/her selection.
var nominalVars = {
state : 'State',
messoreg : 'Messoreg',
reggeoint : 'RegGeoInt',
reggeoimd : 'RegGeoImed',
microreg : 'Microreg',
regmetro : 'RegMetro',
city : 'City',
tipdepe : 'TipDep',
nvldepe : 'NvlDepe',
prefix : 'Prefix',
subord : 'Subord'
};
What I need is to retrieve all the properties bellow the last checkbox checked, e.g., If the user selects [state] checkbox, then I want to get [messoreg], [reggeoint], [reggeoimd], [microreg], etc. and them passing the values to an Array.
I don't know if there is it another way to do that but I'm trying to avoid using Swith of If statements.
Upvotes: 0
Views: 82
Reputation: 443
You should never use an object if you want to keep track of the order. You can use a Map
or an Array
.
The Map object holds key-value pairs and remembers the original insertion order of the keys.
let map = new Map();
map.set('state','State');
map.set('messoreg','Messoreg');
map.set('reggeoint','RegGeoInt');
map.set('reggeoimd','RegGeoImed');
map.set('microreg','Microreg');
map.set('regmetro','RegMetro');
map.set('city','City');
map.set('tipdepe','TipDep');
map.set('nvldepe','NvlDepe');
map.set('prefix','Prefix');
map.set('subord','Subord');
function getKeys(map, afterKey) {
let shouldAdd = false, res = [];
for (const key of map.keys()) {
if (shouldAdd) res.push(key);
if (key === afterKey) shouldAdd = true;
}
return res;
}
function getKeysBefore(map, beforeKey) {
let shouldAdd = true, res = [];
for (const key of map.keys()) {
if (key === beforeKey) shouldAdd = false;
if (shouldAdd) res.push(key);
}
return res;
}
//get keys after 'reggeoint'
let keys;
keys = getKeys(map, 'reggeoint');
document.write(JSON.stringify(keys))
//get keys after 'city'
keys = getKeys(map, 'city');
document.write(JSON.stringify(keys))
//get keys before 'city'
keys = getKeysBefore(map, 'city');
document.write(JSON.stringify(keys))
Upvotes: 2
Reputation: 782466
Use Object.keys()
to get the keys of an obect as an array. Then you can use indexOf()
to get the index of a specific property, and you can slice the rest of the keys.
var nominalVars = {
state: 'State',
messoreg: 'Messoreg',
reggeoint: 'RegGeoInt',
reggeoimd: 'RegGeoImed',
microreg: 'Microreg',
regmetro: 'RegMetro',
city: 'City',
tipdepe: 'TipDep',
nvldepe: 'NvlDepe',
prefix: 'Prefix',
subord: 'Subord'
};
let last_checkbox = "city";
let keys = Object.keys(nominalVars);
let index = keys.indexOf(last_checkbox);
let following_keys = keys.slice(index+1);
console.log(following_keys);
Note that only ES6 requires that the order of object properties to be maintained:
Does ES6 introduce a well-defined order of enumeration for object properties?
Upvotes: 0
Reputation: 243
Object.keys(obj)
Will return the defined keys for any javascript-object. You'll have to filter this array accordingly to match your requirements.
Upvotes: 0