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

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]);
});

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.

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
})
})
})

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();
}

How to transfer input box data to a complex structure JSON

I use jQuery get a JSON string from a API. I want to display it and change some field and PUT back to the API. But it seems to hard to gather information from input box and put it into right field.
Here is the json structure:
{
"economicStatus": "",
"title1": "",
"migrantEducation": "",
"disability": {
"status": "",
"section504Status": "",
"primaryDisability": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"awaitingInitialIDEAEvaluation": ""
},
"giftedTalented": "",
"firstNationalEnrollment": "",
"alertMessageList": [
{
"message": "object",
"messageType": ""
}
],
"medicalAlertMessageList": [
{
"message": "",
"severity": ""
}
],
"projectedGraduationYear": "",
"onTimeGraduationYear": "",
"graduationDate": "",
"economicDisadvantage": "",
"otherIdList": [
{
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
}
],
"name": {
"nameRole": "",
"actualNameOfRecord": {
"prefix": "",
"familyNameFirst": "",
"preferredFamilyNameFirst": "",
"givenName": "",
"middleName": "",
"familyName": "",
"preferredFamilyName": "",
"preferredGivenName": "",
"fullName": "",
"sortName": "",
"suffix": ""
}
},
"phoneNumberList": [
{
"number": "",
"extension": "",
"phoneNumberType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"listedStatus": ""
}
],
"emailList": [
{
"emailAddress": "",
"emailType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
}
],
"localId": {
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
},
"externalId": {
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
},
"addressRefIdList": [
{
"value": "",
"addressRole": ""
}
],
"otherNameList": [
{
"nameRole": "",
"otherName": {
"prefix": "",
"familyNameFirst": "",
"preferredFamilyNameFirst": "",
"givenName": "",
"middleName": "",
"familyName": "",
"preferredFamilyName": "",
"preferredGivenName": "",
"fullName": "",
"sortName": "",
"suffix": ""
}
}
],
"demographics": {
"birthDateVerification": "",
"sexus": "",
"birthDate": "",
"subregionOfBirth": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"stateProvinceOfBirth": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"placeOfBirth": "",
"countryOfBirth": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"countryArrivalDate": "",
"citizenshipStatus": "",
"languageProficiency": "",
"dwellingArrangement": "",
"maritalStatus": "",
"ethnicityList": [
{
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
],
"languageList": [
{
"languageCode": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"languageType": "",
"dialect": ""
}
],
"countryOfResidency": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
},
"countryOfCitizenshipList": [
{
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
]
},
"electronicIdList": [
{
"idValue": "object",
"idType": {
"code": "",
"codesetName": "",
"item": "object",
"otherCodeList": [
{
"value": "",
"codesetName": ""
}
]
}
}
],
"refId": ""
}
And here is a sample data I get back from API, with some field are null:
{
"disability": null,
"economicStatus": null,
"migrantEducation": null,
"title1": null,
"alertMessageList": null,
"medicalAlertMessageList": null,
"projectedGraduationYear": null,
"onTimeGraduationYear": null,
"graduationDate": null,
"giftedTalented": null,
"economicDisadvantage": null,
"firstNationalEnrollment": null,
"otherIdList": [
{
"idType": {
"code": "AuthenticationUsername",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.OtherId"
},
"idValue": "ChK#username-60ty"
},
{
"idType": {
"code": "HMOF UserName",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.OtherId"
},
"idValue": "ChK#username-60ty.arda.stu"
},
{
"idType": {
"code": "Role",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.OtherId"
},
"idValue": "learner"
}
],
"addressRefIdList": null,
"name": null,
"localId": {
"idType": {
"code": "LASID",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.LocalId"
},
"idValue": "79800003270ABCKrtg12"
},
"externalId": {
"idType": {
"code": "SASID",
"item": null,
"otherCodeList": null,
"codesetName": "HMH.ExternalId"
},
"idValue": "NULL"
},
"electronicIdList": null,
"otherNameList": null,
"demographics": null,
"phoneNumberList": null,
"emailList": null,
"refId": "3329962f-18ab-415f-addb-132cbe613d68"
}
Is there a simple way to change the fields in a page using input box? I try to create as many input boxes as needed and name them and associate them with corresponding JSON field... But it seems to tedious and can not update array dynamically.

javascript array object filter on keys

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;
})

Categories