I want to make a table that is separated by pages, and the numbers in the form will not start counting from a new page because of a different page. However, it will count from beginning to end.
For example, this is the first page:
10 XXX
9 XXX
8 XXX
7 XXX
6 XXX
And this is the second page:
5 XXX
4 XXX
3 XXX
2 XXX
1 XXX
However, I could not let it counite counting, and now it happened a problem when I change to the next page:
The counter still like this:
10 XXX
9 XXX
8 XXX
7 XXX
6 XXX
5 XXX
note: the post Notice always appears above, then after that is a normal post.
This my code:
const rawData = [
{
writter: "Admin",
post_admin: true,
new_post: false,
title: "Test",
slug: "test",
code: "230109000001",
created_at: "2023-01-09 15:56:59",
view: 3,
share: 1,
jumlah_like: 0,
jumlah_komen: 4,
},
{
writter: "Dafni Lanahtadya",
post_admin: false,
new_post: false,
title: "pink",
slug: "pink",
code: "230120000112",
created_at: "2023-01-20 13:19:23",
view: 2,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
{
writter: "Dafni Lanahtadya",
post_admin: false,
new_post: false,
title: "weather 3",
slug: "weather-3",
code: "230120000111",
created_at: "2023-01-20 13:16:32",
view: 1,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
{
writter: "Dafni Lanahtadya",
post_admin: false,
new_post: false,
title: "weather 2",
slug: "weather-2",
code: "230120000110",
created_at: "2023-01-20 13:15:10",
view: 2,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
{
writter: "Dafni Lanahtadya",
post_admin: false,
new_post: false,
title: "weather",
slug: "weather",
code: "230120000109",
created_at: "2023-01-20 13:13:47",
view: 1,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
{
writter: "Putri Seprina",
post_admin: false,
new_post: false,
title: "postingan 19 saya",
slug: "postingan-19-saya",
code: "230120000102",
created_at: "2023-01-20 10:08:46",
view: 4,
share: 1,
jumlah_like: 1,
jumlah_komen: 5,
},
{
writter: "Putri Seprina",
post_admin: false,
new_post: false,
title: "postingan 1 saya",
slug: "postingan-1-saya",
code: "230120000056",
created_at: "2023-01-20 10:00:38",
view: 1,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
{
writter: "Dafni Lanahtadya",
post_admin: false,
new_post: false,
title: "57",
slug: "57",
code: "230120000045",
created_at: "2023-01-20 09:58:37",
view: 0,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
{
writter: "Dafni Lanahtadya",
post_admin: false,
new_post: false,
title: "58",
slug: "58",
code: "230120000044",
created_at: "2023-01-20 09:58:22",
view: 0,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
{
writter: "Dafni Lanahtadya",
post_admin: false,
new_post: false,
title: "59",
slug: "59",
code: "230120000043",
created_at: "2023-01-20 09:58:14",
view: 0,
share: 0,
jumlah_like: 0,
jumlah_komen: 0,
},
];
function Index() {
const [listSubPost, setListSubPost] = useState(rawData);
const [countPage, setCountPage] = useState(0);
const [currentPage, setCurrentPage] = useState(1);
const [perPage, setPerPage] = useState(5);
const [dataCount, setDataCount] = useState(31);
const [dataAdminCount, setDataAdminCount] = useState(0);
const [initialPage, setInitialPage] = useState(1);
const setPage = (array, page_size, page_number) => {
// human-readable page numbers usually start with 1, so we reduce 1 in the first argument
setListSubPost(
array.slice((page_number - 1) * page_size, page_number * page_size)
);
};
let _indexUser = 0;
let _countAll = dataCount - dataAdminCount;
return (
<>
<div>
<table
aria-label="Example static collection table"
style={{
height: "auto",
minWidth: "100%",
overflowX: "auto",
}}
>
<thead>
<td>Number</td>
<td>TITLE</td>
<td>WRITER</td>
<td>DATE</td>
<td>LIKES</td>
<td>VIEWS</td>
</thead>
<tbody>
{listSubPost.map((item, index) => {
if (!item?.post_admin) {
_indexUser = _indexUser + 1;
}
return (
<tr key={index}>
<td>
{item?.post_admin
? "Notice"
: _countAll -
(_indexUser - 2) -
Math.ceil(currentPage / perPage)}
</td>
<td>{item.title}</td>
<td>{item.writter}</td>
<td>{item.created_at}</td>
<td>{item.jumlah_like}</td>
<td>{item.view}</td>
</tr>
);
})}
</tbody>
</table>
<button onClick={() => setPage(rawData, 5, 1)}>page 1</button>
<button onClick={() => setPage(rawData, 5, 2)}>page 2</button>
</div>
</>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
thank you all for the answer,
after several hours of searching for the right formula, I finally found the solution.
this for my formula at column Number
{item?.post_admin ? 'Notice' : (dataCount - ((currentPage - 1) * perPage)) - index}
if someone search about my problem or same with my question :)
Related
I have to delete CloudFront distribution using AWS SDK for JavaScript so I'm trying to update it first, but when I sent the request I'm getting Rate exceeded internal server error. I tried many different values inside my config but it always returns this rate error. I'm not sure if it's problem with configuration or maybe I did something else wrong. I have also created function that creates new distribution and it works fine.
My current config object looks like this:
const originId = `S3-${buckets.build.name}`;
const originDomain = `${buckets.build.name}.s3.amazonaws.com`;
const updateParams: CloudFront.UpdateDistributionRequest = {
Id: distribution.id,
IfMatch: distribution.eTag,
DistributionConfig: {
DefaultRootObject: 'index.html',
CallerReference: caller,
Comment: 'Zilo catalog',
DefaultCacheBehavior: {
AllowedMethods: {
Items: ['HEAD', 'GET'],
Quantity: 2,
CachedMethods: {
Items: ['HEAD', 'GET'],
Quantity: 2,
},
},
TargetOriginId: originId,
ViewerProtocolPolicy: 'allow-all',
MinTTL: 3600,
SmoothStreaming: false,
Compress: false,
DefaultTTL: 5000,
FieldLevelEncryptionId: '',
MaxTTL: 10000,
LambdaFunctionAssociations: {
Quantity: 0,
Items: [],
},
ForwardedValues: {
QueryString: true,
Cookies: {
Forward: 'all',
},
Headers: {
Quantity: 0,
Items: [],
},
QueryStringCacheKeys: {
Quantity: 0,
Items: [],
},
},
},
Enabled: false,
Origins: {
Items: [
{
DomainName: originDomain,
Id: originId,
CustomOriginConfig: {
HTTPPort: 80,
HTTPSPort: 443,
OriginProtocolPolicy: 'match-viewer',
OriginSslProtocols: { Items: ['SSLv3'], Quantity: 1 },
OriginReadTimeout: 10000,
OriginKeepaliveTimeout: 10000,
},
OriginPath: '',
CustomHeaders: { Quantity: 0 },
},
],
Quantity: 1,
},
Aliases: {
Quantity: 0,
},
Logging: {
Enabled: false,
IncludeCookies: false,
Bucket: '',
Prefix: '',
},
WebACLId: '',
HttpVersion: 'http2',
Restrictions: {
GeoRestriction: {
RestrictionType: 'none',
Quantity: 0,
},
},
ViewerCertificate: {
MinimumProtocolVersion: 'SSLv3',
},
CustomErrorResponses: {
Items: [],
Quantity: 0,
},
PriceClass: 'PriceClass_100',
CacheBehaviors: { Quantity: 0, Items: [] },
},
};
Any ideas what could gone wrong here?
Ran into this same issue while attempting to disable CloudFront distribution before deleting it. Ended up finding this working solution in Java:
GetDistributionConfigResponse distributionConfigResponse =
cloudFrontClient.getDistributionConfig(GetDistributionConfigRequest.builder().id(distributionId).build());
distributionETag = distributionConfigResponse.eTag();
DistributionConfig originalConfig = distributionConfigResponse.distributionConfig();
UpdateDistributionResponse updateDistributionResponse =
cloudFrontClient.updateDistribution(r -> r.id(distributionId)
.ifMatch(distributionETag)
.distributionConfig(originalConfig.toBuilder()
.enabled(false)
.build()));
I need to parse through and look for a specific id. In the code below I need to be able to pull out the id number. It looks like this "itemIds":["918e337d-82ae-4e91-bdc3-16ad06572e21". I need to be able to pull the number "918e337d-82ae-4e91-bdc3-16ad06572e21". I have been having trouble understanding this concept. If you could send how or the actual code to do it . That would be very much appreciated.
{"dbSessionTokenMap":{"CXO_PC_ST":"e5b96399-fefc-4d9d-93ba-2aa1059008ce|{\"mtoken\":\"301:12#90271897#2=60818072#7=100439087\"}"},"id":"e5b96399-fefc-4d9d-93ba-2aa1059008ce","checkoutFlowType":"Guest","cartId":"ffd6cb2f-efc2-47b2-96d9-52d2cfb3d69b","items":[{"id":"918e337d-82ae-4e91-bdc3-16ad06572e21","offerId":"864A02B3BF7442A4802E6DF7BA2EDA28","productId":"1ZPTYHZN85S6","productName":"Pokemon Assorted Lot of 50 Single Cards [Any Series]","itemId":127446742,"sellerId":"A577588AB81D43AE9E7F468183B3568A","thumbnailUrl":"https://i5.walmartimages.com/asr/aa6ed747-9cd0-44dc-b927-44bc2b7e1ca7_1.62c435484d4015af1c325e9cdeeb3662.jpeg?odnHeight=100&odnWidth=100&odnBg=FFFFFF","legacySellerId":3340,"productClassType":"REGULAR","quantity":1,"unitPrice":8.61,"type":"REGULAR","price":8.61,"unitOfMeasure":"EA","hasCarePlan":false,"brand":"Pok?mon","discount":{},"rhPath":"20000:25000:25003:25114:25333","isWarrantyEligible":false,"category":"0:4171:3318550:617941:8920388","primaryCategory":"Home Page/Toys/Shop Toys by Age/Toys for Kids 5 to 7 Years/Toys for Kids 5 to 7 Years","isCarePlan":false,"isEgiftCard":false,"isAssociateDiscountEligible":false,"isShippingPassEligible":false,"isTwoDayShippingEligible":false,"classId":"5","maxQuantityPerOrder":100,"isSubstitutable":false,"isInstaWatch":false,"isAlcoholic":false,"isSnapEligible":false,"isAgeRestricted":false,"isSubstitutionsAllowed":false,"fulfillmentSelection":{"fulfillmentOption":"S2H","shipMethod":"STANDARD","availableQuantity":172},"servicePlanType":"NONE","errors":[],"wfsEnabled":false,"isAlcohol":false}],"shipping":{"postalCode":"82001","city":"CHEYENNE","state":"WY"},"promotions":[{"promotionId":"1c2cbad1-205e-425f-9297-8629d68e97f6","okToPayAwards":[{"applyTo":"CART_FULFILLMENT_PRICE","actionType":"AWARD","name":"DS_Donors_Choose_Teachers_Card","awardType":"OK_TO_PAY","description":"DonorsChoose Card","applicableTo":{"ITEM_TAX":true,"SHIP_PRICE":true,"SHIP_TAX":true,"FEE":true,"ITEM_PRICE":true},"asset":{"image":"https://i5.walmartimages.com/dfw/63fd9f59-e0cf/455269aa-c4e8-46a5-8d76-5d4b458e1269/v1/Select_gift_card.png","imageAlt":""},"awardEligibleItemIds":[],"awardEligibleTotalsByItemId":{}}],"dsEligibleItemIds":[],"dsEligibleTotals":{}}],"summary":{"subTotal":8.61,"shippingIsEstimate":false,"taxIsEstimate":true,"grandTotal":8.61,"quantityTotal":1,"amountOwed":8.61,"merchandisingFeesTotal":0,"shippingCosts":[{"label":"Top Cut Central shipping","type":"marketplace_shipping","cost":0.0}],"shippingTotal":0.0,"hasSurcharge":false,"preTaxTotal":8.61,"addOnServicesTotal":0,"itemsSubTotal":8.61},"pickupPeople":[],"email":"","buyer":{"customerAccountId":"9afb345e-74b8-4afb-93d0-4bf52697e18f","isGuestSignupRequired":false,"isGuest":true,"isAssociate":false,"applyAssociateDiscount":false},"allowedPaymentTypes":[{"type":"CREDITCARD","cvvRequired":true},{"type":"PAYPAL","cvvRequired":false},{"type":"GIFTCARD","cvvRequired":false},{"type":"VISA_CHECKOUT","cvvRequired":false},{"type":"MASTERPASS","cvvRequired":false},{"type":"CHASEPAY","cvvRequired":false},{"type":"AMEX_CHECKOUT","cvvRequired":false}],"registries":[],"payments":[],"cardsToDisable":[],"allowedPaymentPreferences":[],"isRCFEligible":false,"isMarketPlaceItemsExist":true,"version":"v3","shippingCategory":{"shippingGroups":[{"itemIds":["918e337d-82ae-4e91-bdc3-16ad06572e21"],"seller":"Top Cut Central","defaultSelection":true,"fulfillmentOption":"S2H","shippingGroupOptions":[{"method":"EXPEDITED","methodDisplay":"Expedited","selected":false,"charge":8.99,"deliveryDate":1606766400000,"availableDate":1606766400000,"fulfillmentOption":"S2H","onlineStoreId":0,"isThresholdShipMethod":false},{"method":"STANDARD","methodDisplay":"Standard","selected":true,"charge":0.0,"deliveryDate":1606939200000,"availableDate":1606939200000,"fulfillmentOption":"S2H","onlineStoreId":0,"isThresholdShipMethod":false}],"isEdelivery":false,"hasWFSItem":false,"itemSellerGroups":[]}]},"entityErrors":[],"oneDaySelected":false,"paymentWithBagFee":false,"giftDetails":{"giftOrder":false,"hasGiftEligibleItem":false,"xoGiftingOptIn":false},"canApplyDetails":[],"dbName":"e5b96399-fefc-4d9d-93ba-2aa1059008ce|C","jwt":"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1MjdmZTRjYi0wZjI5LTRjZWYtOWRiOS00Yzc1YWQ5MTMwNTQiLCJpYXQiOjE2MDYwOTY0NjMsImlzcyI6IjU3YjM0ZTNhZGE1MjkzMGEwYzBjYTFjOSIsIk9yZ1VuaXRJZCI6IjU2ZWJiMTJkZGE1MjkzMWRhOGZlMDc5YSIsIlJlZmVyZW5jZUlkIjoiZTViOTYzOTktZmVmYy00ZDlkLTkzYmEtMmFhMTA1OTAwOGNlIn0.-ta5UQLkJtXNR5yP2dOhDiDMF9dPpbfktAJu7z22kNM"}
Edit Below! Edit Below! Edit Below!
For future visitors -
I like to use split to find what I specifically need. For example for this problem I had above. I would just use
let myId = string.split(`"itemIds":["`)[1].split('"')[0]
This should work well and I use this method all the time. If you have any better methods feel free to reply or leave an answer. You can also use JSON.parse(your data) and look for your specific variable that way. This article should also help you understand how to use it. https://www.tutorialrepublic.com/javascript-tutorial/javascript-json-parsing.php
First you need to determine which prop will you get the value of? And then try this, in this case I will get "itemIds" so my findProp function will take 2 parameters:
const myObj = {
dbSessionTokenMap: {
CXO_PC_ST:
'e5b96399-fefc-4d9d-93ba-2aa1059008ce|{"mtoken":"301:12#90271897#2=60818072#7=100439087"}',
},
id: "e5b96399-fefc-4d9d-93ba-2aa1059008ce",
checkoutFlowType: "Guest",
cartId: "ffd6cb2f-efc2-47b2-96d9-52d2cfb3d69b",
items: [
{
id: "918e337d-82ae-4e91-bdc3-16ad06572e21",
offerId: "864A02B3BF7442A4802E6DF7BA2EDA28",
productId: "1ZPTYHZN85S6",
productName: "Pokemon Assorted Lot of 50 Single Cards [Any Series]",
itemId: 127446742,
sellerId: "A577588AB81D43AE9E7F468183B3568A",
thumbnailUrl:
"https://i5.walmartimages.com/asr/aa6ed747-9cd0-44dc-b927-44bc2b7e1ca7_1.62c435484d4015af1c325e9cdeeb3662.jpeg?odnHeight=100&odnWidth=100&odnBg=FFFFFF",
legacySellerId: 3340,
productClassType: "REGULAR",
quantity: 1,
unitPrice: 8.61,
type: "REGULAR",
price: 8.61,
unitOfMeasure: "EA",
hasCarePlan: false,
brand: "Pok?mon",
discount: {},
rhPath: "20000:25000:25003:25114:25333",
isWarrantyEligible: false,
category: "0:4171:3318550:617941:8920388",
primaryCategory:
"Home Page/Toys/Shop Toys by Age/Toys for Kids 5 to 7 Years/Toys for Kids 5 to 7 Years",
isCarePlan: false,
isEgiftCard: false,
isAssociateDiscountEligible: false,
isShippingPassEligible: false,
isTwoDayShippingEligible: false,
classId: "5",
maxQuantityPerOrder: 100,
isSubstitutable: false,
isInstaWatch: false,
isAlcoholic: false,
isSnapEligible: false,
isAgeRestricted: false,
isSubstitutionsAllowed: false,
fulfillmentSelection: {
fulfillmentOption: "S2H",
shipMethod: "STANDARD",
availableQuantity: 172,
},
servicePlanType: "NONE",
errors: [],
wfsEnabled: false,
isAlcohol: false,
},
],
shipping: { postalCode: "82001", city: "CHEYENNE", state: "WY" },
promotions: [
{
promotionId: "1c2cbad1-205e-425f-9297-8629d68e97f6",
okToPayAwards: [
{
applyTo: "CART_FULFILLMENT_PRICE",
actionType: "AWARD",
name: "DS_Donors_Choose_Teachers_Card",
awardType: "OK_TO_PAY",
description: "DonorsChoose Card",
applicableTo: {
ITEM_TAX: true,
SHIP_PRICE: true,
SHIP_TAX: true,
FEE: true,
ITEM_PRICE: true,
},
asset: {
image:
"https://i5.walmartimages.com/dfw/63fd9f59-e0cf/455269aa-c4e8-46a5-8d76-5d4b458e1269/v1/Select_gift_card.png",
imageAlt: "",
},
awardEligibleItemIds: [],
awardEligibleTotalsByItemId: {},
},
],
dsEligibleItemIds: [],
dsEligibleTotals: {},
},
],
summary: {
subTotal: 8.61,
shippingIsEstimate: false,
taxIsEstimate: true,
grandTotal: 8.61,
quantityTotal: 1,
amountOwed: 8.61,
merchandisingFeesTotal: 0,
shippingCosts: [
{
label: "Top Cut Central shipping",
type: "marketplace_shipping",
cost: 0.0,
},
],
shippingTotal: 0.0,
hasSurcharge: false,
preTaxTotal: 8.61,
addOnServicesTotal: 0,
itemsSubTotal: 8.61,
},
pickupPeople: [],
email: "",
buyer: {
customerAccountId: "9afb345e-74b8-4afb-93d0-4bf52697e18f",
isGuestSignupRequired: false,
isGuest: true,
isAssociate: false,
applyAssociateDiscount: false,
},
allowedPaymentTypes: [
{ type: "CREDITCARD", cvvRequired: true },
{ type: "PAYPAL", cvvRequired: false },
{ type: "GIFTCARD", cvvRequired: false },
{ type: "VISA_CHECKOUT", cvvRequired: false },
{ type: "MASTERPASS", cvvRequired: false },
{ type: "CHASEPAY", cvvRequired: false },
{ type: "AMEX_CHECKOUT", cvvRequired: false },
],
registries: [],
payments: [],
cardsToDisable: [],
allowedPaymentPreferences: [],
isRCFEligible: false,
isMarketPlaceItemsExist: true,
version: "v3",
shippingCategory: {
shippingGroups: [
{
itemIds: ["918e337d-82ae-4e91-bdc3-16ad06572e21"],
seller: "Top Cut Central",
defaultSelection: true,
fulfillmentOption: "S2H",
shippingGroupOptions: [
{
method: "EXPEDITED",
methodDisplay: "Expedited",
selected: false,
charge: 8.99,
deliveryDate: 1606766400000,
availableDate: 1606766400000,
fulfillmentOption: "S2H",
onlineStoreId: 0,
isThresholdShipMethod: false,
},
{
method: "STANDARD",
methodDisplay: "Standard",
selected: true,
charge: 0.0,
deliveryDate: 1606939200000,
availableDate: 1606939200000,
fulfillmentOption: "S2H",
onlineStoreId: 0,
isThresholdShipMethod: false,
},
],
isEdelivery: false,
hasWFSItem: false,
itemSellerGroups: [],
},
],
},
entityErrors: [],
oneDaySelected: false,
paymentWithBagFee: false,
giftDetails: {
giftOrder: false,
hasGiftEligibleItem: false,
xoGiftingOptIn: false,
},
canApplyDetails: [],
dbName: "e5b96399-fefc-4d9d-93ba-2aa1059008ce|C",
jwt:
"eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1MjdmZTRjYi0wZjI5LTRjZWYtOWRiOS00Yzc1YWQ5MTMwNTQiLCJpYXQiOjE2MDYwOTY0NjMsImlzcyI6IjU3YjM0ZTNhZGE1MjkzMGEwYzBjYTFjOSIsIk9yZ1VuaXRJZCI6IjU2ZWJiMTJkZGE1MjkzMWRhOGZlMDc5YSIsIlJlZmVyZW5jZUlkIjoiZTViOTYzOTktZmVmYy00ZDlkLTkzYmEtMmFhMTA1OTAwOGNlIn0.-ta5UQLkJtXNR5yP2dOhDiDMF9dPpbfktAJu7z22kNM",
};
const findProp = (obj, prop, out) => {
let i,
proto = Object.prototype,
ts = proto.toString,
hasOwn = proto.hasOwnProperty.bind(obj);
if ("[object Array]" !== ts.call(out)) {
out = [];
}
for (i in obj) {
if (hasOwn(i)) {
if (i === prop) {
out.push(obj[i]);
} else if (
"[object Array]" === ts.call(obj[i]) ||
"[object Object]" === ts.call(obj[i])
) {
findProp(obj[i], prop, out);
}
}
}
return out;
};
console.log(findProp(myObj, "itemIds"));
I have a menu array called "items".
It has submenus.
I need to filter the items with property "visible" equal 1.
I don't know at run time how deep the hierarchy will be.
I need a function returning a new array, with the next conditions:
Every non-matching object with no children, or no matches in children hierarchy, should not exist in output object
Every object with a descendant that contains a matching object, should remain
Only descendants with matching objects should remain
My question is similar to this post Recursively filter array of objects.
But it does not work to me.
I have used the following function, but it´s not working:
const items = [ { icon: "mdi-view-dashboard", title: "Dashboard", to: "/", visible: 1, },
{ title: "Manutenção", icon: "mdi-hammer-screwdriver", to: "", visible: 1,
items: [
{ title: "Usuários", icon: "mdi-account", to: "/usuarios", visible: 1, },
{ title: "Cores", to: "", visible: 1,
items: [
{ title: "Cores da Fila", icon: "mdi-eyedropper-variant", to: "/coresfila", visible: 1, },
{ title: "Cores da Agenda", icon: "mdi-palette", to: "/coresagenda", visible: 1, },
],
},
{ title: "Tabelas Médicas", to: "", visible: 1,
items: [
{ title: "Convênios", icon: "mdi-clipboard-outline", to: "/convenios", visible: 1, },
{ title: "Planos", icon: "mdi-plus-box", to: "/planos", visible: 1, },
{ title: "Especialidades", icon: "mdi-format-font", to: "/especialidadescompletas", visible: 1, },
{ title: "Modelos de Atestados", icon: "mdi-account-details-outline", to: "/modelosAtestados", visible: 1, },
{ title: "Modelos de Prescrições", icon: "mdi-account-edit-outline", to: "/modelosPrescricoes", },
{ title: "Cid-10", icon: "mdi-alphabetical", to: "/cid10", visible: 1, },
{ title: "Procedimentos", icon: "mdi-alarm-plus", to: "/procedimentos", visible: 1, },
{ title: "Materiais", icon: "mdi-table-of-contents", to: "/materiais", visible: 1, },
{ title: "Medicamentos", icon: "mdi-water", to: "/medicamentos", visible: 1, },
{ title: "Taxas", icon: "mdi-cash-100", to: "/taxas", visible: 1, },
],
},
],
},
{ title: "Empresa", icon: "mdi-cash-100", to: "", visible: 1,
items: [ { title: "Perfil da Empresa", icon: "mdi-account-network-outline", to: "/perfilempresa", visible: 1, },
{ title: "Créditos SMS", icon: "mdi-cash-usd-outline", to: "/creditossms", visible: 1, },
],
},
{ title: "Clientes", icon: "mdi-account-alert-outline", to: "/clientes", visible: 1, },
{ title: "Agenda", icon: "far fa-calendar-check", to: "/agenda", visible: 1, },
{ title: "Fila", icon: "mdi-account-multiple-check", to: "/fila", visible: 1, },
{ title: "Atendimento Médico", icon: "fas fa-user-md", to: "/atendimento", visible: 1, },
{ title: "Tela de Chamadas", icon: "mdi-play-network-outline", to: "/telao", visible: 1, },
{ title: "DICOM", icon: "mdi-radioactive-off", to: "/dicom", visible: 1, },
{ title: "Estatísticas", icon: "mdi-chart-box", to: "", visible: 1,
items: [ { title: "Clientes", icon: "mdi-account-arrow-right", to: "", visible: 1,
items: [ { title: "Por convênios", icon: "mdi-poll", to: "/estat_cliente_por_convenios", visible: 1, },
{ title: "Por mês", icon: "mdi-poll", to: "/estat_cliente_por_mes", visible: 1, },
],
},
{ title: "Faturamento", icon: "mdi-cash-usd", to: "", visible: 1,
items: [ { title: "Por convênios", icon: "mdi-poll", to: "/estat_faturamento_por_convenios", visible: 1, },
{ title: "Por mês", icon: "mdi-poll", to: "/estat_faturamento_por_mes", visible: 1, },
], },
], },
{ title: "Autorizações", icon: "mdi-microphone-variant", to: "/listaautorizacoes", visible: 1, },
{ title: "Faturamento", icon: "mdi-cash-usd", to: "", visible: 1,
items: [ { title: "Nova Guia", icon: "mdi-cart-plus", to: "/guiasfaturas", visible: 0, },
{ title: "Lista Guias", icon: "mdi-tray-plus", to: "/listaguias", visible: 1, },
{ title: "Lote de Guias", icon: "mdi-bag-personal", to: "/loteguias", visible: 1, }, ], },
]
function ofilter(arr) {
var matches = [];
if (!Array.isArray(arr)) return matches;
arr.forEach(function(i) {
if (i.visible && i.visible === 1) {
matches.push(i);
} else {
let childResults = this.ofilter(i.items);
if (childResults.length)
matches.push(Object.assign({}, i, {
items: childResults
}));
}
});
return matches;
}
console.log(ofilter(items))
Here's a recursive filter based on a recursive visibility check. This version preserves the nested structure:
const isVisible = item => item.visible
|| item.items?.some(isVisible)
const filterItems = items => {
items.forEach(item => {
if (item.items) item.items = filterItems(item.items)
})
return items.filter(isVisible)
}
console.log(filterItems(
[
{ id: 'a', visible: 1 },
{ id: 'b', visible: 0 },
{
id: 'c',
visible: 0,
items: [
{ id: 'd', visible: 1 },
{ id: 'e', visible: 0 }
]
},
{ id: 'f', visible: 1, items: [{ id: 'g', visible: 0 }] },
{ id: 'h', visible: 0, items: [{ id: 'i', visible: 0 }] },
]
))
Alternatively, here's a version that returns a flat array:
const filterItemsFlat = (items, results = []) => {
items.forEach(item => {
if (item.items) filterItemsFlat(item.items, results)
if (item.visible) results.push(item)
})
results.forEach(r => delete r.items)
return results
}
console.log(filterItemsFlat(
[
{ id: 'a', visible: 1 },
{ id: 'b', visible: 0 },
{
id: 'c',
visible: 0,
items: [
{ id: 'd', visible: 1 },
{ id: 'e', visible: 0 }
]
},
{ id: 'f', visible: 1, items: [{ id: 'g', visible: 0 }] },
{ id: 'h', visible: 0, items: [{ id: 'i', visible: 0 }] },
]
))
Another alternative to question:
const items = [
{ icon: "mdi-view-dashboard", title: "Dashboard", to: "/", visible: 1, },
{ title: "Manutenção", icon: "mdi-hammer-screwdriver", to: "", visible: 0,
items: [
{ title: "Usuários", icon: "mdi-account", to: "/usuarios", visible: 1, },
{ title: "Cores", to: "", visible: 0}
]
}
];
function ofilter(arr) {
let r = [];
arr.forEach((i) => {
if (i.visible == 1) {
r.push(i);
}
if (i.items) {
r.push(ofilter(i.items))
}
})
return r;
}
console.log('result:', ofilter(items))
I am using Tabulator to create the table and adding a button to print out the table, however, when i click the button it shows the progress bar in my table doesn't show on the print out results. Does anyone know why i can not print out the progress bar? Thank you.
var tabledata = [{
id: 1,
name: "postp_ckmb_ngml_group_>=5.6",
confidence: "1.08",
acceptable: "true"
},
{
id: 2,
name: "pci_status_cd_急诊",
confidence: "1.05",
acceptable: "true"
},
{
id: 3,
name: "conclision_angiography_type_冠脉三支病变",
confidence: "1.01",
acceptable: "true"
},
{
id: 4,
name: "pci_indication_cd_STEMI的紧急PCI治疗",
confidence: "0.89",
acceptable: "true"
},
{
id: 5,
name: "postp_bnp_pnml_group_>500",
confidence: "0.82",
acceptable: "true"
},
{
id: 6,
name: "postp_bnp_pnml_group_100-500",
confidence: "0.82",
acceptable: "true"
},
{
id: 7,
name: "cad_presentation_cd_STEMI(7天)",
confidence: "0.79",
acceptable: "true"
},
{
id: 8,
name: "pci_status_cd_早期",
confidence: "0.64",
acceptable: "true"
},
{
id: 9,
name: "cad_presentation_cd_Non-STEMI(7天)",
confidence: "0.61",
acceptable: "true"
},
{
id: 10,
name: "if_pior_cvd_1.0",
confidence: "0.37",
acceptable: "true"
}
];
const table = new Tabulator("#tableContainer", {
data: tabledata,
height: "292px",
layout: "fitColumns",
printAsHtml: true,
printCopyStyle: true,
printHeader: "<h3>Feature Selection Results<h3>",
columns: [{
title: "",
field: "id",
width: 50
},
{
title: "Feature",
field: "name"
},
{
title: "Confidence",
field: "confidence",
sorter: "number",
align: "left",
formatter: "progress",
width: 400,
formatterParams: {
mix: 0,
max: 1.1,
color: ["#296FAB"],
legend: true,
legendColor: "#333333",
legendAlign: "right"
}
},
{
title: "Acceptability",
field: "acceptable",
align: "center",
editor: true,
sorter: "boolean",
formatter: "tickCross",
width: 150
},
],
});
const printTable = () => {
table.print(false, true);
}
<script src="https://unpkg.com/tabulator-tables#4.3.0/dist/js/tabulator.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.3.0/css/tabulator.min.css" rel="stylesheet" />
<button onclick="printTable()">Print
</button>
<div id="tableContainer"></div>
I want to use the print out button to print out the entire table include the progress bar.
This was a limitation of the original Tabulator print system only being able to handle text based formatters
As of version 4.6, released mid 2020, you should have no problem printing graphical formatters
I had used for loop to iterate nested objects, I am trying to replace forEach with the map function, without success. Can anyone help me with this?
schema.js
const products_schema = {
product_name: {
auto: false,
type: "string",
min: 5,
max: 10,
special_characters: ['_', ' '],
numbers: true,
alphabet: true,
required: true,
correct: ""
},
product_image: {
auto: false,
type: "array:string",
min: 0,
max: 50,
required: true
}
}
const specification_schema = {
brand: {
auto: false,
type: "string",
min: 10,
max: 50,
special_characters: ['_', ' '],
numbers: true,
alphabet: true,
required: true
}
}
let schema = {
products_schema:products_schema,
specification_schema:specification_schema
}
for(var key in schema)
{
var value = schema[key]
Object.keys(value).forEach(key => console.log(value[key].type));
}
"Expected output:"
string
array:string
string
use Object.values then use map to return only type property.
const products_schema = {
product_name: {
auto: false,
type: "string",
min: 5,
max: 10,
special_characters: ['_', ' '],
numbers: true,
alphabet: true,
required: true,
correct: ""
},
product_image: {
auto: false,
type: "array:string",
min: 0,
max: 50,
required: true
}
}
const specification_schema = {
brand: {
auto: false,
type: "string",
min: 10,
max: 50,
special_characters: ['_', ' '],
numbers: true,
alphabet: true,
required: true
}
}
let schema = {
products_schema:products_schema,
specification_schema:specification_schema
}
const mergedObjects = {...products_schema, ...specification_schema};
const output = Object.values(mergedObjects).map(({type}) => type);
console.log(output);
You could use nested Object.values():
const products_schema={product_name:{auto:false,type:"string",min:5,max:10,special_characters:['_',' '],numbers:true,alphabet:true,required:true,correct:""},product_image:{auto:false,type:"array:string",min:0,max:50,required:true}},
specification_schema={brand:{auto:false,type:"string",min:10,max:50,special_characters:['_',' '],numbers:true,alphabet:true,required:true}},
schema={ products_schema, specification_schema }
Object.values(schema).forEach(o => {
Object.values(o).forEach(a => console.log(a.type))
})
If you want to get an array of nested type you could use flatMap
const products_schema={product_name:{auto:false,type:"string",min:5,max:10,special_characters:['_',' '],numbers:true,alphabet:true,required:true,correct:""},product_image:{auto:false,type:"array:string",min:0,max:50,required:true}},
specification_schema={brand:{auto:false,type:"string",min:10,max:50,special_characters:['_',' '],numbers:true,alphabet:true,required:true}},
schema={ products_schema, specification_schema }
const types = Object.values(schema).flatMap(o =>
Object.values(o).map(a => a.type)
)
console.log(types)
If flatMap is not supported, you could simply use the first snippet and push to an array instead of logging it to the console.
const output = [];
Object.values(schema).forEach(o =>
Object.values(o).forEach(a => output.push(a.type))
)