javascript array object filter on keys - javascript

I have a javascript db in the format
var db = [
{ "id": "500020", "type": "0", "address": "", "firstName": "bob", "lastName": "builder", "title": "Mr", "managerId": "0", "officeId": "222", "cellPhone": "", "officePhone": "001221212121", "email": "myemail#domain.com", "Hours": "", "Custface": "", "Hearloop": "", "Parking": "", "Toilets": "", "Wheelchair": "", "OfficeType": "", "lat": "", "lon": "", "Company": "mycompany","image": "1111" },
{ "id": "500025", "type": "0", "address": "", "firstName": "danny", "lastName": "mccanny", "title": "Mr", "managerId": "0", "officeId": "0", "cellPhone": "", "officePhone": "012545251", "email": "Danny#mccanny.com", "Hours": "", "Custface": "", "Hearloop": "", "Parking": "", "Toilets": "", "Wheelchair": "", "OfficeType": "", "lat": "", "lon": "", "Company": "dannycompany","image": "500025" }
]
I then reference it like this
this.employees = db;
in a function I then filter it when a user searches like this
var employees = this.employees.filter(function (element) {
var fullname = element.firstname + " " + element.lastname;
return fullname.tolowercase().indexof(searchkey.tolowercase()) > -1;
});
the problem is that it is searching every element of the object not just the firstName and the lastName.
Can someone tell me how to get it to filter on just the first and last name using either javascript or jquery

We can use jquery grep method to filter the data and the code will be
var employees = $.grep(this.employees, function(element){
var fullname = element.firstName + " " + element.lastName;
return fullname.toLowerCase().indexOf(searchkey.toLowerCase()) > -1;
})

Related

WooCommerece RestAPI - NodeJS

Im using wc rest api with nodejs and when trying to post new order via "orders" with method POST, I simply get response containing all the existing orders..
Even if not providing any request body, or providing false request body - same response always:
WooCommerce.post("orders", {
customer_id: 2000,
})
.then((response) => {
res.send(response.data);
})
.catch((err) => {
res.status(500).send(e.response.data);
});
Response:
[
{
"id": 32941,
"parent_id": 0,
"status": "pending",
"currency": "ILS",
"version": "5.3.1",
"prices_include_tax": false,
"date_created": "2022-02-17T11:23:28",
"date_modified": "2022-02-17T11:24:39",
"discount_total": "0.00",
"discount_tax": "0.00",
"shipping_total": "0.00",
"shipping_tax": "0.00",
"cart_tax": "0.00",
"total": "9.90",
"total_tax": "0.00",
"customer_id": 110,
"order_key": "wc_order_Gv1ZIlKqqMKFt",
"billing": {
"first_name": "",
"last_name": "",
"company": "",
"address_1": "",
"address_2": "",
"city": "",
"state": "",
"postcode": "",
"country": "",
"email": "raz#king.com",
"phone": ""
},
"shipping": {
"first_name": "",
"last_name": "",
"company": "",
"address_1": "",
"address_2": "",
"city": "",
"state": "",
"postcode": "",
"country": ""
},
"payment_method": "",
"payment_method_title": "",
"transaction_id": "",
"customer_ip_address": "",
"customer_user_agent": "",
"created_via": "admin",
"customer_note": "",
"date_completed": null,
"date_paid": null,
"cart_hash": "",
"number": "32941",
"meta_data": [],
"line_items": [
{
"id": 3267,
"name": "מלפפון",
"product_id": 32409,
"variation_id": 0,
"quantity": 1,
"tax_class": "",
"subtotal": "9.90",
"subtotal_tax": "0.00",
"total": "9.90",
"total_tax": "0.00",
"taxes": [],
"meta_data": [],
"sku": "10864",
"price": 9.9,
"parent_name": null
}
],
"tax_lines": [],
"shipping_lines": [],
"fee_lines": [],
"coupon_lines": [],
"refunds": [],
"date_created_gmt": "2022-02-17T09:23:28",
"date_modified_gmt": "2022-02-17T09:24:39",
"date_completed_gmt": null,
"date_paid_gmt": null,
"currency_symbol": "₪",
"_links": {
"self": [
{
"href": "https://XXX.XXX.XXX/wp-json/wc/v3/orders/32941"
}
],
"collection": [
{
"href": "https://XXX.XXX.XXX/wp-json/wc/v3/orders"
}
],
"customer": [
{
"href": "https://XXX.XXX.XXX/wp-json/wc/v3/customers/110"
}
]
}
}
]
Please be aware that I've masked some data :)
WooCommerce.post("orders?_method=POST", order)
.then((response) => {
res.send(response.data);
})
.catch((e) => {
console.log(e);
res
.status(e?.response?.status || 500)
.send(e?.response?.statusText || e?.response?.data || "Error!");
});
Found on google that need to use native http methods like get or post and pass in the param ?_method=METHOD to define what method to use....
Working.

Partition data from array and store in variable (Javascript / JSON)

I have a requirement where I need to partition incoming data to look like the following example:
//required payload
{
"campaign_id": "",
"recipient": {
"first_name": "",
"last_name": "",
"company": "",
"email": "",
"address_1": "",
"city": "",
"state": "",
"postal_code": "",
"identifier": ""
}
}
However, my issue is that the payload currently being posted to my endpoint looks like this:
//entire payload
"body": {
"info": [
{
"campaign_id": "",
"recipient": {
"first_name": "",
"last_name": "",
"company": "",
"email": "",
"address_1": "",
"city": "",
"state": "",
"postal_code": "",
"identifier": ""
}
}
],
"otherArray": [],
"otherString": "",
"otherString2": ""
}
}
What I want to do is extract the required data in my first example from the second example and then store it in a variable. Something like the below:
var requiredPayload = {"campaign_id": "", "recipient": {}};
What can I do to put campaign_id + recipient object in a single variable?
We should be able to assign the first element of the info array to the requiredPayload variable, like so:
const payload = {
"body": {
"info": [
{
"campaign_id": "",
"recipient": {
"first_name": "",
"last_name": "",
"company": "",
"email": "",
"address_1": "",
"city": "",
"state": "",
"postal_code": "",
"identifier": ""
}
}
],
"otherArray": [],
"otherString": "",
"otherString2": ""
}
};
var requiredPayload = payload.body.info[0];
console.log("requiredPayload:", requiredPayload);
try this:
var data={"body": {
"info": [
{
"campaign_id": "",
"recipient": {
"first_name": "",
"last_name": "",
"company": "",
"email": "",
"address_1": "",
"city": "",
"state": "",
"postal_code": "",
"identifier": ""
}
}
],
"otherArray": [],
"otherString": "",
"otherString2": ""
}
};
console.log(data.body.info[0]); //data is variable name
var info_data=data.body.info[0];
if info have multiple campaign_id then try this
$.each(data.body.info, function (indexInArray, valueOfElement) {
console.log(data.body.info[indexInArray]);
});

Is there a way to remove from JSON but keep its content?

I have a JSon like this :
[
{
"order_number": "",
"products": [
{
"line_id": "" ,
"cod_anf": "",
"static_field_2": "",
"nome_armazem": "",
"cod_armazem": "",
"gln": "",
"sku_ah": "",
"name": "",
"qty": "",
"_regular_price": "",
"_sale_price": "",
"line_total": "",
"desconto": "",
"pva": "",
"category": "",
"localidade": " ",
"codigo_ah": " ",
"Part of": ""
},
{
"line_id": "",
"cod_anf": "",
"static_field_2": "",
"nome_armazem": "",
}
],
{
"order_number": "",
"products": [
{
"line_id": 1,
"cod_anf": "",
"static_field_2": "",
I need to remove the "products" but keep it's content.
So the output should be like this:
Is it possible? I've tried and I cant make it work.
Thanks
You can use nested maps, spread operator, and flat function like below.
const json = [{
"order_number": "2",
"products": [{
"line_id": "",
"cod_anf": "",
"static_field_2": "",
"nome_armazem": "",
"cod_armazem": "",
"gln": "",
"sku_ah": "",
"name": "",
"qty": "",
"_regular_price": "",
"_sale_price": "",
"line_total": "",
"desconto": "",
"pva": "",
"category": "",
"localidade": " ",
"codigo_ah": " ",
"Part of": ""
},
{
"line_id": "",
"cod_anf": "",
"static_field_2": "",
"nome_armazem": "",
}
]
},
{
"order_number": "1",
"products": [{
"line_id": 1,
"cod_anf": "",
"static_field_2": "",
}
]
}
];
const flattened = json.map(r => [...r.products.map(q =>
({
order_number: r.order_number,
...q
})
)])
.flat(1);
console.log(flattened);
Try this, assign json to data
let obj = [];
data.forEach(order =>{
order.products.forEach(product => {
obj.push({
...product,
order_number: order.order_number
})
})
})

Put two different associative arrays inside one associative array as an array with two associative arrays in javascript

I Want to join two arrays into one array containing two different arrays
First Array. I do not mean a simple array but this time around a more complex array with field having the same values on both sides of the arrays.
var arr1 = [{
"id": "4",
"ip_address": "127.0.0.1",
"username": "superuser",
"password": "$2y$08$awherOdjNPRoDHAiNBGZNuA92UGfT7jsIpsMMcNnyyJMxBA8Ug9q6",
"salt": null,
"email": "super#admin.com",
"activation_code": null,
"forgotten_password_code": "NULL",
"forgotten_password_time": null,
"remember_code": "cBjcajHj8qXaNrOhkAAqPe",
"created_on": "2018-09-13",
"last_login": "1540549332",
"active": "1",
"first_name": "Super",
"last_name": "Admin",
"phone": "0",
"user_id": "4",
"groups": [{
"id": "10",
"name": "superusers",
"description": "Super Administrators",
"$$hashKey": "object:38"
}],
"$$hashKey": "object:11"
}];
var arr2 = [{
"id": "1",
"ip_address": "127.0.0.1",
"username": "administrator",
"password": "$2y$08$DoULTzDyGFyh.DTNOvxRtujA3CT2yVBMpp6joYnfUcD0FQgbm9rmy",
"salt": "",
"email": "admin#admin.com",
"activation_code": "",
"forgotten_password_code": null,
"forgotten_password_time": null,
"remember_code": "wYiqzg7AM2QbEPdVrqUhkO",
"created_on": "2010-03-18",
"last_login": "1537468397",
"active": "1",
"first_name": "Admin",
"last_name": "istrator",
"phone": "0",
"user_id": "1",
"groups": [{
"id": "3",
"name": "admins",
"description": "Administrators",
"$$hashKey": "object:32"
}],
"$$hashKey": "object:8"
}];
let's say you declared your arrays as arr1 and arr2. To merge them:
var $users = arr1.concat(arr2);
If you want $users to be an array with two elements, and each of one being an array, you would do
var $users = [arr1, arr2];
But that doesn't match your desired result and it would make little sense.
var a = [10, 20];
var b = [30, 40, 50];
Array.prototype.push.apply(a,b);
console.log(a);
var arr1 = [{
"id": "4",
"ip_address": "127.0.0.1",
"username": "superuser",
"password": "$2y$08$awherOdjNPRoDHAiNBGZNuA92UGfT7jsIpsMMcNnyyJMxBA8Ug9q6",
"salt": null,
"email": "super#admin.com",
"activation_code": null,
"forgotten_password_code": "NULL",
"forgotten_password_time": null,
"remember_code": "cBjcajHj8qXaNrOhkAAqPe",
"created_on": "2018-09-13",
"last_login": "1540549332",
"active": "1",
"first_name": "Super",
"last_name": "Admin",
"phone": "0",
"user_id": "4",
"groups": [{
"id": "10",
"name": "superusers",
"description": "Super Administrators",
"$$hashKey": "object:38"
}],
"$$hashKey": "object:11"
}];
var arr2 = [{
"id": "1",
"ip_address": "127.0.0.1",
"username": "administrator",
"password": "$2y$08$DoULTzDyGFyh.DTNOvxRtujA3CT2yVBMpp6joYnfUcD0FQgbm9rmy",
"salt": "",
"email": "admin#admin.com",
"activation_code": "",
"forgotten_password_code": null,
"forgotten_password_time": null,
"remember_code": "wYiqzg7AM2QbEPdVrqUhkO",
"created_on": "2010-03-18",
"last_login": "1537468397",
"active": "1",
"first_name": "Admin",
"last_name": "istrator",
"phone": "0",
"user_id": "1",
"groups": [{
"id": "3",
"name": "admins",
"description": "Administrators",
"$$hashKey": "object:32"
}],
"$$hashKey": "object:8"
}];
let $users = arr1.concat(arr2);
console.log($users);
Concatenate both arrays using concat function
const arr1 = [/\*values\*/];
const arr2 = [/\*values\*/];
// As in description:
const $users = arr1.concat(arr2); //[firstValues, secondValues]
// As in title:
const $users = [arr1, arr2]; //[[firstValues], [secondValues]]

Use Javascript object variable for an if statement

I'm using javascript to display information of a shop basket. I know how to pull the data and create elements from it, but I need to use one of the variables for an if statement, and am unsure how to.
If this is true: "isPunchOut": false, then I want to target that with jQuery, and do something like $(".button").remove();
How do I do this?
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"isPunchOut": false,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"shippingFormatSum": "\u20AC0",
"orderno": "0",
"orderFormatSum": "\u20AC130",
"voucher": "",
"orderFormatVat": "\u20AC27,30",
"currencySymbol": "\u20AC",
"currency": "EUR",
"orderVat": 27.3,
"orderSum": 130.0,
"items": [{
"imageURI": "\/imgr\/8c82380c-65f5-43aa-83ad-fae1215b5b39\/70\/70",
"qtyAvail": 7,
"price": 130.0,
"qty": 1,
"artno": "D630-T7100-GE-REF",
"vat": 27.3,
"formatVat": "\u20AC27,30",
"id": "52307",
"label": "D630 C2D-T7100/2GB/80GB/DVD/14"/NO COA WLAN",
"category": "Computers - Notebooks",
"formatPrice": "\u20AC130",
"manufacturer": "Dell"
}]
}
}
You can take a look at below JS code for reference:
var isPunchOut = retailerData["user"]["isPunchOut"];
if(isPunchOut === false)
$(".button").remove();
I would say you should try some code first and put where you get stuck .We not here to write code for your problems.
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"isPunchOut": false,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"shippingFormatSum": "\u20AC0",
"orderno": "0",
"orderFormatSum": "\u20AC130",
"voucher": "",
"orderFormatVat": "\u20AC27,30",
"currencySymbol": "\u20AC",
"currency": "EUR",
"orderVat": 27.3,
"orderSum": 130.0,
"items": [{
"imageURI": "\/imgr\/8c82380c-65f5-43aa-83ad-fae1215b5b39\/70\/70",
"qtyAvail": 7,
"price": 130.0,
"qty": 1,
"artno": "D630-T7100-GE-REF",
"vat": 27.3,
"formatVat": "\u20AC27,30",
"id": "52307",
"label": "D630 C2D-T7100/2GB/80GB/DVD/14"/NO COA WLAN",
"category": "Computers - Notebooks",
"formatPrice": "\u20AC130",
"manufacturer": "Dell"
}]
}
}
if(retailerData.user.isPunchOut){
//your jquery operation
}
Checkjsfiddle
What about?
if (!retailerData.user.isPunchOut) {
$(".button").remove();
}

Categories