so, I have the USPS entire CITY, STATE, COUNTY, LAT LON, and ZIP CODE as seen below in the example from said JSON. It's 349,000 lines long. Very cool.
...
{
"zip_code": 988,
"latitude": 18.393355,
"longitude": -65.972495,
"city": "Carolina",
"state": "PR",
"county": "Carolina"
},
{
"zip_code": 1001,
"latitude": 42.140549,
"longitude": -72.788661,
"city": "Agawam",
"state": "MA",
"county": "Hampden"
},
...
As you can see, the upper Zip Code has only three digits and the next one, in order has 4 then later down the line there are finally 5 digits.
What I need to do is LOOP through all Zip Codes that === 3 && === 4 and add TWO ZEROS for those Zips with 3 digits and ONE ZERO for Zips with 4 digits.
This NEEDS to be on the fly or need to do a GLOBAL search and replace, ONE TIME, so the add'l Zeros are already there. This comes from the USPS without the leading zeros.
citystatezip is imported like so
import * as citystatezip from 'src/assets/json/city-state-zip-county.json';
Here's what I've tried... or am trying:
/**
* @name getAllZips
* @description gets all the Zips
* @returns OBJECT Any
*/
getAllZipCodes(): any {
let zips = [];
zips = _.map(citystatezip as unknown as any, 'zip_code');
let result = _.find(zips, function (n) {
if (n === 3) {
????????????????
} else if (n === 4) {
????????????????
}
}, 0)
return result;
}
UPDATE: Added this as a solution from @Kelly
getAllZipCodes(): any {
let zips = [];
zips = _.map(citystatezip as unknown as any, 'zip_code');
let result = _.find(zips, function (n) {
n.toString().padStart(5, "0")
}, 0)
return result;
}
The problem, not with @Kellys solution, is it's not going into the "IF" statement.
Remember, there are 43,625 cities, which is 349000/8 which is the {} and the 6 lines in each. Am I not doing the _.find correctly?
UPDATE 2:
/**
* @description set and gets all zip codes
* @argument nothing
* @returns zipcodes for get
*/
public setZipCodes(): void {
this.zipcodes = this.getAllZipCodes();
}
public getZipCodes(): Object {
return this.zipcodes;
}
/**
* @name getAllZips
* @description gets all the Zips
* @returns OBJECT Any
*/
getAllZipCodes(): any {
let zips = [];
zips = _.map(citystatezip as unknown as any, 'zip_code');
let result = _.find(zips, function (n) {
return n.toString().padStart(5, "0") <<< like so???
}, 0)
this.zipcodes = result;
return result;
}
and in the COMPONENT calling the SERVICE above, here's the code in ngOnInit()
this.allCities = this.elementService.getCities();
this.allStates = this.elementService.getStates();
this.allZipcodes = this.vaForm21elementService.getZipCodes();
console.log("All cities: ", this.allCities);
console.log("All states: ", this.allStates.default);
console.log("All zip codes: ", this.allZipcodes);
CodePudding user response:
Replace _.find
with map
:
let result = zips.map((n) => n.toString().padStart(5, "0"));
padStart
pads the start of the string:
988 => 00988
1001 => 01001
31553 => 31553