I have
var lookupMap. This is an excerpt:
{ ANDERSON: { county: 'ANDERSON', code: 'us-tx-001' },
ANDREWS: { county: 'ANDREWS', code: 'us-tx-003' } ,
WARD: { county: 'WARD', code: 'us-tx-475' },
WASHINGTON: { county: 'WASHINGTON', code: 'us-tx-477' },
WEBB: { county: 'WEBB', code: 'us-tx-479' }}
It is a long index of counties, and their corresponding code. Not all will be used.
I have var uniquedata, which looks like:
[ 'us-tx-477', 'us-tx-479' ]
which is an array of codes.
I also have var results, which looks like:
{ WASHINGTON: 9, WEBB: 4 }.
Basically, what i want to do now is go through elements from uniquedata, and for each one, look up the county it belongs to, and replace the county name with the code, but keep the count the same.
So, for example, the output should be:
{ 'us-tx-477' : 9,
'us-tx-479': 4}
What is the best way to do this? I'm having troubles trying to isolate elements...it seems really confusing & I can't wrap my head around it.
Iterate through each item in uniquedata and do a lookup in the data object. The function findInLookupMap
goes through each object in lookupmap and returns the county name for a code.
Something like this
var cache = {};
function findInLookupMap(key){
if(cache[key]) return cache[key]; // <--- cache to avoid looping in further requests
for(var o in data){
if(data[o].code == key){
cache[key] = data[o].county;
return data[o].county;
}
}
}
var output = {};
for(var i=0;i<uniquedata.length;i++){ // <--- iterate through each item in uniquedata
var code = findInLookupMap(uniquedata[i]);
output[uniquedata[i]] = results[code];
}
console.log(output);
var lookupMap = { "ANDERSON": { "county": 'ANDERSON', "code": 'us-tx-001' }, "ANDREWS": { "county": 'ANDREWS', "code": 'us-tx-003' }, "WARD": { "county": 'WARD', "code": 'us-tx-475' }, "WASHINGTON": { "county": 'WASHINGTON', "code": 'us-tx-477' }, "WEBB": { "county": 'WEBB', "code": 'us-tx-479' } }; var uniquedata = ['us-tx-477', 'us-tx-479']; var results = { WASHINGTON: 9, WEBB: 4 }; var cache = {}; function findInLookupMap(key) { if (cache[key]) return cache[key]; for (var o in lookupMap) { if (lookupMap[o].code == key) { cache[key] = lookupMap[o].county; return lookupMap[o].county; } } } var output = {}; for (var i = 0; i < uniquedata.length; i++) { var code = findInLookupMap(uniquedata[i]); output[uniquedata[i]] = results[code]; } console.log(output);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.