I am using react-table to render data from an API in tabular format. The data shows plant sowing data across multiple years and species and I use the url params from react router to filter the returned data to show relevant info on the appropriate route.
The data returned from the API is like
{
"result": [
{
"_id": "63dba20f9d8e2bb7569e991a",
"common_name": "Tomato Sun Grape",
"date": "2022-12-26T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "2022-12-30T00:00:00.000Z",
"first_harvest": "",
"genus": "Solanum",
"last_harvest": "",
"number_germinated": "",
"number_sown": 7,
"planted_out": "",
"species": "lycopersicum",
"year": 2022
},
{
"_id": "63dba20f9d8e2bb7569e991c",
"common_name": "Pepper (Sweet) Lany",
"date": "2022-12-26T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "2023-01-03T00:00:00.000Z",
"first_harvest": "",
"genus": "Capsicum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "annuum",
"year": 2022
},
{
"_id": "63dba20f9d8e2bb7569e991d",
"common_name": "Pepper (Chilli) Bhut Jolokia",
"date": "2022-12-26T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "2023-01-10T00:00:00.000Z",
"first_harvest": "",
"genus": "Capsicum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "chinense",
"year": 2022
},
{
"_id": "63dba20f9d8e2bb7569e9919",
"common_name": "Tomato Big Mama",
"date": "2022-12-26T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "2022-12-30T00:00:00.000Z",
"first_harvest": "",
"genus": "Solanum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "lycopersicum",
"year": 2022
},
{
"_id": "63dba20f9d8e2bb7569e991f",
"common_name": "Thai Basil",
"date": "2022-12-26T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "2022-12-31T00:00:00.000Z",
"first_harvest": "",
"genus": "Ocimum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "basilicum",
"year": 2022
},
{
"_id": "63dba2569d8e2bb7569ea752",
"common_name": "Pepper (Chilli) Bhut Jolokia",
"date": "2023-02-02T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "",
"first_harvest": "",
"genus": "Capsicum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "chinense",
"year": 2023
}
]
}
I then filter this array based on url params e.g.:/username/:genus (/jinky32/Capsicum)
const filteredSowings = (sowingArray, filters) => {
let filtered = sowingArray.filter((card) =>
Object.entries(filters).every(([key, value]) => card[key] === value)
);
return filtered;
};
to get the sowings of that genus by the user as dictated by the route. The filtered data looks like this:
[
{
"_id": "63dba20f9d8e2bb7569e991c",
"common_name": "Pepper (Sweet) Lany",
"date": "2022-12-26T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "2023-01-03T00:00:00.000Z",
"first_harvest": "",
"genus": "Capsicum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "annuum",
"year": 2022
},
{
"_id": "63dba20f9d8e2bb7569e991d",
"common_name": "Pepper (Chilli) Bhut Jolokia",
"date": "2022-12-26T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "2023-01-10T00:00:00.000Z",
"first_harvest": "",
"genus": "Capsicum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "chinense",
"year": 2022
},
{
"_id": "63dba2569d8e2bb7569ea752",
"common_name": "Pepper (Chilli) Bhut Jolokia",
"date": "2023-02-02T00:00:00.000Z",
"sow_number": "",
"userName": "jinky32",
"comments": "",
"first_germinated": "",
"first_harvest": "",
"genus": "Capsicum",
"last_harvest": "",
"number_germinated": "",
"number_sown": "",
"planted_out": "",
"species": "chinense",
"year": 2023
}
]
This all works well but the filtered data includes sowings across multiple years (2022 and 2023 in this case) and I would like to render a table for each year there were sowings for a particular species. Actually, this is a specific instance of the requirement, the generic requirement is to be able to return a table per specified object property value - for example on a route :/username/:genus I might instead want to return a table for each unique species in that genus
I tried to use map function data.map below (where data is the filtered array) but this renders the table the same number of times as the number of items in the array.
return (
<>
{data ? (
<>
<h1>{location.pathname.split("/")[2]} Sowings</h1>
<Row>
{data.map((sowing) => (
<Table striped bordered hover responsive {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<th {...column.getHeaderProps()}>
{column.render("Header")}
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return (
<td {...cell.getCellProps()}>
{cell.render("Cell")}
</td>
);
})}
</tr>
);
})}
</tbody>
</Table>
))}
</Row>
</>
) : (
<h1>Data not here</h1>
)}
</>
);
The current code returns the below
but I am trying to achieve an output such as the below (where I may need to group by species rather than year)
Any help would be very much appreciated!
Related
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.
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]);
});
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
})
})
})
I made a website and I just can't manage to search by multidimensional array / object (I don’t know what the difference is).
Before adding the year and month, I accessed them directly by identifier array[id][field]
how to implement search by nested structures in a multidimensional array
I tried to pre-define the year and month with additional fields in the interface.
and it looks creepy and incomprehensible.
{
"2018": {
"Aug": {
"1": {
"id": 1,
"appeal_date": "2018-08-24",
"city_of_residence": "aaa",
"patient_name": "John",
"patient_age": 62,
"coordinator": "aaa",
"source": "aaa",
"birth_date": "1956-06-30",
"contact_person_name": "",
"contact_person_role": "",
"contact_person_phones": [
"",
""
],
"diagnosis": "aasasd",
"status": "9",
"departure_date": "2016-02-18",
"arrival_date": "2020-01-23",
"patient_phones": [
"",
""
],
"editable": true
}
}
},
"2019": {
"Oct": {
"65": {
"id": 65,
"appeal_date": "2019-10-18",
"city_of_residence": "asfsac",
"patient_name": "asvsas",
"patient_age": 62,
"coordinator": "",
"source": "asfasfa",
"birth_date": "1956-06-30",
"contact_person_name": "",
"contact_person_role": "",
"contact_person_phones": "",
"diagnosis": "assdbcx",
"status": "1",
"departure_date": "",
"arrival_date": "",
"patient_phones": "",
"editable": true
}
},
"Jun": {
"64": {
"id": 64,
"appeal_date": "2019-06-04",
"city_of_residence": "afsfsa",
"patient_name": "asvac",
"patient_age": 62,
"coordinator": "",
"source": "agwdawdawd",
"birth_date": "1956-06-30",
"contact_person_name": "",
"contact_person_role": "",
"contact_person_phones": "",
"diagnosis": "agsags",
"status": "1",
"departure_date": "",
"arrival_date": "",
"patient_phones": "",
"editable": true
}
}
}
}
all i need is to update some fields in the right object
patients [2019] ['Oct'] [65] ['diagnosis'] = 'aaaaa'
something like this, but in a certain month the patient may not be right
I would like something like this:
patients.nestingSearchByKey (65) ['diagnosis'] = 'aaaaa'
their identifiers are unique and not repeated
I apologize for my English
any ideas please
You can use Object.keys to get an array of keys in the object.
var pts = {
"2018": {
"Aug": {
"1": {
"id": 1,
"appeal_date": "2018-08-24",
"city_of_residence": "aaa",
"patient_name": "John",
"patient_age": 62,
"coordinator": "aaa",
"source": "aaa",
"birth_date": "1956-06-30",
"contact_person_name": "",
"contact_person_role": "",
"contact_person_phones": [
"",
""
],
"diagnosis": "aasasd",
"status": "9",
"departure_date": "2016-02-18",
"arrival_date": "2020-01-23",
"patient_phones": [
"",
""
],
"editable": true
}
}
},
"2019": {
"Oct": {
"65": {
"id": 65,
"appeal_date": "2019-10-18",
"city_of_residence": "asfsac",
"patient_name": "asvsas",
"patient_age": 62,
"coordinator": "",
"source": "asfasfa",
"birth_date": "1956-06-30",
"contact_person_name": "",
"contact_person_role": "",
"contact_person_phones": "",
"diagnosis": "assdbcx",
"status": "1",
"departure_date": "",
"arrival_date": "",
"patient_phones": "",
"editable": true
}
},
"Jun": {
"64": {
"id": 64,
"appeal_date": "2019-06-04",
"city_of_residence": "afsfsa",
"patient_name": "asvac",
"patient_age": 62,
"coordinator": "",
"source": "agwdawdawd",
"birth_date": "1956-06-30",
"contact_person_name": "",
"contact_person_role": "",
"contact_person_phones": "",
"diagnosis": "agsags",
"status": "1",
"departure_date": "",
"arrival_date": "",
"patient_phones": "",
"editable": true
}
}
}
}
function search(patients, id) {
var patient;
const years = Object.keys(patients);
years.forEach(year => {
const months = Object.keys(patients[year]);
months.forEach(month => {
if (patients[year][month][id]) {
patient = patients[year][month][id];
}
});
});
return patient;
}
const p = search(pts, 64);
if (p) {
p['status'] = 0;
console.log(pts);
} else {
console.log('Not find patient with id 64');
}
If I understood you currectly and you're keeping the current object structure, you just need to check for patient existence:
var patient = patients[2019]['Oct'][65];
if (patient) {
patient['diagnosis'] = 'aaaaa';
}
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;
})