How to get values from an array of objects using a KEY and creating a new array of values with LODASH - lodash

I have this array of Objects (it's a snippet of greater city, state, zip
[{
"city": "Picardville",
"state": "MA",
"zip": "11119"
},{
"city": "Picardville",
"state": "MA",
"zip": "11120"
},
{
"city": "Kirktown",
"state": "MA",
"zip": "11121"
},
{
"city": "Janewayville",
"state": "MA",
"zip": "11122"
},
{
"city": "Kahnville",
"state": "MA",
"zip": "11123"
}
]
So, if I push in a ZIP CODE, I want to make a new array that will SHOW all the cities for a ZIP and the STATE...Because cities can have multiple zipcodes, let's say I push in 11219, I would ONLY get the first one, but, if I enter PICARDVILLE in the CITY field, the ZIP codes that I can only choose from are: 11119 and 11120. The state would default to MA.
My thought is, without using Google Maps or Smarty Streets, my company wants me to do it this way. I've DONE it before with AngularJS back in 2016 but that was using uib-typeahead which is gone.
My code for Autopopulating CITY and STATE with ZIP code being entered is this.
autoSetCity(zip: string): string {
let cityname = '';
_.forOwn(citystatezip, function (value: any, key: any) {
if (value.zip_code === zip) {
cityname = value.city;
return;
}
});
console.log('CityName: ' + cityname);
return cityname;
}
autoSetState(zip: string): string {
let statename = '';
_.forOwn(citystatezip, function (value: any, key: any) {
if (value.zip_code === zip) {
statename = value.state;
return;
}
});
console.log('CityName: ' + statename);
return statename;
}
But it doesn't.
BTW, citystatezip is HUGE and contains all the CITIES, STATES, ZIPS, COUNTIES and LAT LONs for every ZIP code.
here's a sample:
{
"zip_code": 76465,
"latitude": 32.215275,
"longitude": -98.207997,
"city": "Morgan Mill",
"state": "TX",
"county": "Erath"
},
{
"zip_code": 76466,
"latitude": 32.442088,
"longitude": -98.734228,
"city": "Olden",
"state": "TX",
"county": "Eastland"
},
{
"zip_code": 76467,
"latitude": 32.341365,
"longitude": -97.932083,
"city": "Paluxy",
"state": "TX",
"county": "Hood"
},

I figured it out;
Here's my SERVICE layer
getCitiesAndStateBasedOnzip(zip: any): any {
const self = this;
let csz = this.allCityStateZip.data;
console.log('CSZ: ', csz);
for (let i = 0; i < csz.length; i++) {
if (csz[i].zip_code === zip * 1) {
self.cszctylatlon.city = csz[i].city;
self.cszctylatlon.state = csz[i].state;
self.cszctylatlon.county = csz[i].county;
self.cszctylatlon.country = 'USA';
self.cszctylatlon.zip = csz[i].zip_code;
self.cszctylatlon.lat = csz[i].latitude;
self.cszctylatlon.lon = csz[i].longitude;
}
}
console.log('Reduced City, State, Zip Object: ', this.cszctylatlon);
return this.cszctylatlon;
}
Here's where I get the info calling the service layer from the component
if (event.target.name === 'homezip') {
let zip = '';
zip = this.theform.value.homezip;
if (zip) {
let result = this.vaForm21elementService.getCitiesAndStateBasedOnzip(zip);
this.theform.patchValue({'homecity': result.city});
this.theform.patchValue({'homeprovince': result.county});
this.theform.patchValue({'homestate': result.state});
this.theform.patchValue({'homelat': result.lat});
this.theform.patchValue({'homelon': result.lon});
this.theform.patchValue({'homecountry': result.country});
this.theform.patchValue({'homeaddress': this.theform.value.homeaddressline1 + ' ' + this.theform.value.homeaddressline2 + ' ' + this.theform.value.homeaptnumber + ' ' + this.theform.value.homecity + ', ' + this.theform.value.homestate + ' ' + this.theform.value.homezip})
} else {
this.errmsg = 'No ZIP CODE Given';
console.log(this.errmsg);
return;
}
}
That's pretty much it.
I used TYPEAHEAD for the zip code and populate, CITY, STATE, COUNTY, LAT LON, and COUNTRY.
DONE!

Related

How to break line in vue-multiselect on options

Actually my main problem is about putting breakline inside options in javascript. I've problem with to break line on options when using multiselect with Vue.js.
Multiselect looks like this:
<multiselect v-model="form4.user_id"
:options="users"
:searchable="true"
:preselect-first="true"
:loading="is_loading_customers"
:internal-search="false"
:custom-label="with_customer_custom_label"
#search-change="get_customers_data"
track-by="id"
selected-label=""
select-label=""
deselect-label=""
placeholder="Ad, soyad, TC veya telefon numarası ile aratın..."
id="folder-status-select">
</multiselect>
My with_customer_custom_label function:
const with_customer_custom_label = ({ customer_detail }) => {
return `
TC: ${customer_detail.tc_identity_number} |
Ad Soyad: ${customer_detail.fullname} |
Telefon: ${customer_detail.phone}
`;
};
Options (users):
const users = ref([]);
// and then...
const get_customers_data = (query) => {
if (query.length > 2) {
is_loading_customers.value = true;
var axios_params = new URLSearchParams();
axios_params.append('query', query);
store.state.ax_req_auth.get('/search-customers', {
params: axios_params,
}).then(response => {
users.value = response.data;
is_loading_customers.value = false;
}).catch(error => {
console.log(error);
is_loading_customers.value = false;
});
}
};
response.data return example:
{
"id": "9832a4c7-38cb-4422-a8f3-18f024f31653",
"username": "customer",
"email": "customer#ferisoft.com",
"user_type": "4",
"status": "1",
"email_verified": "1",
"email_verified_at": "2023-01-11T10:26:43.000000Z",
"created_at": "2023-01-11T10:26:43.000000Z",
"updated_at": "2023-01-11T10:26:43.000000Z",
"customer_detail": {
"id": "9832a4c7-c4fe-4f4c-98b9-ab55c9e40265",
"user_id": "9832a4c7-38cb-4422-a8f3-18f024f31653",
"name": "Semih",
"surname": "ŞAHİN",
"tc_identity_number": "99999999990",
"phone": "05555555555",
"date_of_birth": "2023-01-11 10:26:43",
"profession": "0",
"salary": 22500,
"premium": 4000,
"start_date_of_work": "2023-01-11 10:26:43",
"close_to_customer_name": "Ferkan",
"close_to_customer_surname": "AKYAZICI",
"close_to_customer_tc_identity_number": "98989999992",
"close_to_customer_phone": "05527516134",
"email_address": "semih#ferisoft.com",
"profile_picture": null,
"notes": "Krediye şu şu şu sebeplerden dolayı ihtiyacım var, şu şu şu banka geçmişim var.",
"created_at": "2023-01-11T10:26:43.000000Z",
"updated_at": "2023-01-11T10:26:43.000000Z",
"fullname": "Semih ŞAHİN"
}
}
I want to embed with break line the option element to multiselect in the with_customer_custom_label function.
I already tried these:
return `
TC: ${customer_detail.tc_identity_number}\n
Ad Soyad: ${customer_detail.fullname}\n
Telefon: ${customer_detail.phone}
`;
or
return `
TC: ${customer_detail.tc_identity_number}` + "\n" + `
Ad Soyad: ${customer_detail.fullname}` + "\n" + `
Telefon: ${customer_detail.phone}
`;
But they always appear side by side. How can I show one under the other or with break line?

Filter the JSON object where value is not empty or not null on created function on vue.js 3

I want to get the response.data (JSON Object) with value only in the new object on update form i.e. I want to filter it on computed/created on vue 3 - the json object received from API. My backend is Laravel 8 resource API.
On EditPatient.vue - The vue js is
export default {
data() {
return {
patient: {},
}
},
created() {
this.$axios.get('/sanctum/csrf-cookie').then(response => {
this.$axios.get(`/api/patients/${this.$route.params.id}`)
.then(response => {
this.patient = response.data // JSON object
/* .filter(function(item) {
item !== null || item !=='';
}) */ // this didn't work.
//I want to response.data and apply to this.patient object.
})
.catch(function (error) {
console.error(error);
});
})
},
}
response.data is
{ "created_by": 1, "firstname": "Kamal", "lastname": "", "sex": "M", "address": "Kathmandu, Bagmati, Nepal", "education": "Yes", "grade": "MSc", "alcohol": null, "alcohol_type": null, "weight": "", "kidney_disease": null, "high_bp": "No", "diabetes": null, "heart_attack_stroke": "No", "present_diabetes": "No", "systolic": "", "pulse_rate": "" }
On laravel api, I got a patient row as follow:
public function show($id)
{
$patient = Patient::find($id);
return response()->json($patient); // send data in json ojbect for frontend
}
It is better, If I can apply on backend too. Get the columns of single row which has value only.
To get only the object properties that are not empty/null:
Use Object.entries() on the response.data object to get an array of key/value pairs.
Use Array.prototype.filter() on the result, filtering out empty string and null.
Use Object.fromEntries() on the filtered result to create an object.
const input = { "created_by": 1, "firstname": "Kamal", "lastname": "", "sex": "M", "address": "Kathmandu, Bagmati, Nepal", "education": "Yes", "grade": "MSc", "alcohol": null, "alcohol_type": null, "weight": "", "kidney_disease": null, "high_bp": "No", "diabetes": null, "heart_attack_stroke": "No", "present_diabetes": "No", "systolic": "", "pulse_rate": "" }
const entries = Object.entries(input) // 1️⃣
const nonEmptyOrNull = entries.filter(([key,val]) => val !== '' && val !== null) // 2️⃣
const output = Object.fromEntries(nonEmptyOrNull) // 3️⃣
console.log(output)

slice, groupBy []array

I've got all servere problems by as a []array. Problem is how to slice(groupBy) status,bootable. I just wanna take as status = available, bootable = false
Controller
slicedBy := make(map[string]interface{})
server := blockstorage.ListVolumes(tenantID.(string)) <----- this is array
for _, sg := range server{
slicedBy[sg.ID] = sg.Status <------- slice by Status
slicedBy[sg.ID] = sg.Bootable <------- slice by Bootable
}
Json array
{
id 123
status available
bootable false
...
}
server as array
[
{
"id": "a8b123fc-a141-4682-b65b-d56899621959",
"status": "available",
"size": 1,
"availability_zone": "nova",
"attachments": [],
"name": "snapshot 1",
"description": "",
"bootable": "false",
},
{
"id": "ccb734d4-c098-4929-8ce5-281b6a58421d",
"status": "error",
"size": 2,
"availability_zone": "nova",
"attachments": [],
"name": "",
"description": "",
"volume_type": "",
"bootable": "false",
"volume_image_metadata": {
"signature_verified": "False"
}
},
for _, sg := range server {
if(sg.Status == "available" && sg.Bootable == "false"){
jsons["Data"] = sg
}
}
It worked perfectly. I just found it.

Lodash : Extent by adding to attribute

[
{
"Office_Id": 100,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "test"
},
{
"Office_Id": 200,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "test"
},
{
"Office_Id": 300,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "test"
}
]
Using lodash how can i add a new attribute by combining Office_Id And OfficeName
{
"Office_Id": 300,
"Address1": "xxxxx",
"Address2": "",
"City": "ANNISTON",
"District_Id": 1277,
"OfficeName": "offce_ttttt",
"office": "300 - offce_ttttt"
}
In mutating the original objects:
offices = _.forEach(offices, function (o) {
_.assign(o, { office: o.Office_Id + ' - ' + o.OfficeName })
})
Without mutating the original objects:
var newObjects = _.map(offices, function (o) {
return _.assign({}, o, { office: o.Office_Id + ' - ' + o.OfficeName })
})

Datatables with nested array

I've posed a question about Bootstrap Tables but meanwhile I moved to Datatables as I was feeling blocked. My problem, however, is the same.
None of the two can easily handle nested JSON results. For instance if I choose "field: author", it processes the following as "[Object Object], [Object Object]".
"author": [
{
"family": "Obama",
"given": "Barack"
},
{
"family": "Obama",
"given": "Michelle"
}
I can select the results individually, say "field: author[, ].family", which returns a list like "Obama, Obama". But I want an output like "given+family1, given+family2, ..".
You can use custom rendering. DataTables allows you to define custom rendering for each column.
Here is a sample that I worked out. I am doing custom rendering for Author column.
$(document).ready(function() {
var dataSet = [
{ "name": "How to DataTables", "author": [{ "firstname": "jack", lastname: "d" }, { "firstname": "dick", lastname: "j" }] },
{ "name": "How to Custom Render", "author": [{ "firstname": "bill", lastname: "g" }, { "firstname": "scott", lastname: "g" }] }
];
$('#example').DataTable({
data: dataSet,
columns: [
{ title:"Book Name",
data: "name" },
{
title: "Authors",
data: "author",
render: function(data, type, row) {
//return data.length;
var txt = '';
data.forEach(function(item) {
if (txt.length > 0) {
txt += ', '
}
txt += item.firstname + ' ' + item.lastname;
});
return txt;
}
}
]
});
});