Can console log fetched array but cant get the values - javascript

So I can call the variable "teams" and see the data fine but I can't get the values from it in my {#each} block. I know its not part of the "fixtures" variable I'm iterating through and tbh that's probably the issue.
Does anyone know how I can get the actual values within "teams" instead of getting 'undefined' or a better way of fetching multiple arrays within themselves? (ill put the example at the bottom)
my +page.svelte
<script>
export let data;
const { fixtures } = data;
const teams = fixtures.flatMap(fixtures => fixtures.participants)
console.log(teams)
</script>
<div class="flex flex-col absolute top-[0] right-0 w-[85vw] p-6">
<div class="">
{#each fixtures as fixture}
<p>{fixture.name}</p>
<div class="">{fixture.home_score}{fixture.away_score}</div>
<p>{teams.short_code}</p>
{/each}
</div>
</div>
+page.server.js
export const load = async () => {
const fetchList= async () => {
const url = `https://api.sportmonks.com/v3/football/schedules/seasons/19734?api_token=${process.env.API_KEY}`;
const res = await fetch(url);
const data = await res.json()
return data.data.flatMap(data => data.rounds.map(rounds => rounds.fixtures)).flat()
}
return {
fixtures: fetchList(),
}
}
The API
{
"data": [
{
"id": 77457864,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"type_id": 223,
"name": "Regular Season",
"sort_order": 1,
"finished": false,
"is_current": true,
"starting_at": "2022-08-05",
"ending_at": "2023-05-28",
"rounds": [
{
"id": 274668,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"name": "1",
"finished": true,
"is_current": false,
"starting_at": "2022-08-05",
"ending_at": "2022-08-07",
"fixtures": [
{
"id": 18535049,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"group_id": null,
"aggregate_id": null,
"round_id": 274668,
"state_id": 5,
"venue_id": 206,
"name": "Manchester United vs Brighton & Hove Albion",
"home_score": 1,
"away_score": 2,
"starting_at": "2022-08-07 13:00:00",
"result_info": "Brighton & Hove Albion won after full-time.",
"leg": "1/1",
"details": null,
"length": 90,
"placeholder": false,
"last_processed_at": "2022-12-05 09:15:37",
"starting_at_timestamp": 1659877200,
"participants": [
{
"id": 14,
"sport_id": 1,
"country_id": 462,
"venue_id": 206,
"gender": "male",
"name": "Manchester United",
"short_code": "MUN",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/14.png",
"founded": 1878,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-10 17:00:00",
"meta": {
"location": "home"
}
},
{
"id": 78,
"sport_id": 1,
"country_id": 462,
"venue_id": 480,
"gender": "male",
"name": "Brighton & Hove Albion",
"short_code": "BRH",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/78.png",
"founded": 1901,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-08 13:00:00",
"meta": {
"location": "away"
}
}
]
},

There's a "dirty" way to do it with {#key}

Related

Core Javascript Question -- Delete Object in a json file sourced from a column if conditions meet

the reason I need the code to work in core javascript is the tool we use, it uses Rhino from mozilla, so it cannot contain objects or methods related to manipulation of web pages.
I am trying to compare data from two json files using core javascript, When the order_number and extid is same we compare the count(fullfilments.line_items) and quantity(which is the sum of all the quantities of all line items under that fulfillment, fullfilments.line_items.quantity) . If the order_number and ext_id combination match along with count and sum above, do nothing. If no match, we remove the refund. the code works fine in Visual Studio. I am new to pentaho and I think the code needs to be changed as only core js works with this tool.
In the Orders file are sample json structure, for example Order_number (66 in this case) need to calculate and compare the count of line items(6 in this case) along with the Quantity of items(7 in this case), if it doesn't match need to remove Object Refund along with its elements, else No Changes.
``````Sample File````````
[
{
"app_id": 111,
"fulfillments":
[
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 66,
"ext_id": 110,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 398000,
"order_id": 450005,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 67,
"ext_id": 114,
"refunds": [
{
"id": 81,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 2
},
{
"id": 768,
"quantity": 2
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 68,
"ext_id": 113,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
}
]
```````````````````````````````json`````````````
//resultset file content
[
{
"order_number": 66,
"extid":110,
"line_items_count": 6,
"quantity": 7
},
{
"order_number": 67,
"extid":114,
"line_items_count": 4,
"quantity": 7
},
{
"order_number": 68,
"extid":113,
"line_items_count": 4,
"quantity": 6
}
]
`````````````````````````````````````````````````Code`````````````````
/**
* orders.json file has some sample orders
* resultset.json file has results from sql Lookup to the orders.
*
*/
const orders = require('./orders.json');
function compare(order) {
let isMatched = false;
let resultSet = require('./resultset.json');
let result = resultSet.find(function (item) {
return item.order_number === order.order_number;
});
if (
result &&
result.line_items_count === order.items &&
result.quantity === order.quantity
) {
isMatched = true;
}
return isMatched;
}
function fixOrders(orders) {
orders.map(function (order) {
let { order_number, line_items } = order;
let quantity = line_items.reduce(function (quantity, line_item) {
return (quantity += line_item.quantity);
}, 0);
if (!compare({ order_number, items: line_items.length, quantity })) {
delete order.refunds;
}
});
return orders;
}
let fixedOrders = fixOrders(orders);
console.log(fixedOrders);
// store in output.js
//========================================
// var fs = require('fs');
// fs.writeFile('outputFile.json', JSON.stringify(fixedOrders), (err) => {
// if (err) console.log(err);
// else {
// console.log('File written successfully\n');
// // console.log('The written has the following contents:');
// // console.log(fs.readFileSync('outputFile.json', 'utf8'));
// }
// });
[PDI Flow][1]
[1]: https://i.stack.imgur.com/3OzQE.png

Show Result routing path with Leaflet

I get route between 2 Point :
{
"routes": [
{
"overview_polyline": {
"points": "m{f~D}_ygHp#wAJs#Is#eAsBGk#Hg#"
},
"legs": [
{
"summary": "میدان انقلاب - انقلاب",
"distance": {
"value": 209.0,
"text": "۲۲۵ متر"
},
"duration": {
"value": 13.0,
"text": "کمتر از ۱ دقیقه"
},
"steps": [
{
"name": "بزرگراه اهواز-حمیدیه",
"instruction": "در جهت شرق در بزرگراه اهواز-حمیدیه قرار بگیرید",
"bearing_after": 119,
"type": "depart",
"distance": {
"value": 25.0,
"text": "۲۵ متر"
},
"duration": {
"value": 1.0,
"text": "کمتر از ۱ دقیقه"
},
"polyline": "m{f~D}_ygHTm#",
"start_location": [
48.629912,
31.333827
]
},
{
"name": "انقلاب",
"instruction": "در میدان انقلاب، از خروجی دوم، خارج شوید",
"rotaryName": "میدان انقلاب",
"bearing_after": 126,
"type": "rotary",
"modifier": "straight",
"exit": 2,
"distance": {
"value": 101.0,
"text": "۱۲۵ متر"
},
"duration": {
"value": 5.0,
"text": "کمتر از ۱ دقیقه"
},
"polyline": "wzf~DkaygHNWJQJs#Is#Yk#",
"start_location": [
48.630143,
31.333717
]
},
{
"name": "",
"instruction": "به مسیر خود ادامه دهید",
"bearing_after": 53,
"type": "exit rotary",
"modifier": "straight",
"exit": 2,
"distance": {
"value": 83.0,
"text": "۱۰۰ متر"
},
"duration": {
"value": 8.0,
"text": "کمتر از ۱ دقیقه"
},
"polyline": "szf~DigygHk#gAGk#Hg#",
"start_location": [
48.631088,
31.333703
]
},
{
"name": "انقلاب",
"instruction": "در مقصد قرار دارید",
"bearing_after": 0,
"type": "arrive",
"distance": {
"value": 0.0,
"text": ""
},
"duration": {
"value": 0.0,
"text": ""
},
"polyline": "}{f~DelygH",
"start_location": [
48.631869,
31.333913
]
}
]
}
]
}
]
}
In Steps we have 4 points:
[31.333827,48.629912 ],
[31.333717,48.630143 ],
[31.333703,48.631088],
[31.333913,48.631869 ]
When I use polyline my output is like below picture. But real Path is another thing.
I use Leaflet and get my .png file for map from another server and get Json String from another server.
How can Manage this?
A Map Matching API should solve your problem.
Google Snap to Roads API
Mapbox Map Matching API
There also seems to be some open source alternatives like the Valhalla Map Matching API
What was the original directions API request? Curious to see why you're getting that result for that route

Replacing two objects in an array

I am trying to develop a dynamic DraggableFlatList with react native redux, where the updated array from onDragEnd is dispatched to the store. Hence I am trying to create a function where I use the "from" and "to" parameters from the return object from onDragEnd to alter a new array before dispatch. As an example, in the object below, I work with three items, that are objects from the array:
Object {
"data": Array [
Object {
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
},
Object {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
},
Object {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": Object {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
},
],
"from": 2,
"to": 1,
}
Here I would like the object with the description "two" to change place with the object with the description "one." The keys don't matter because I give them new keys when I render during render.
The function that is doing the replacement looks like this so far:
const dragComplete = (item) => {
let itemArray = item.data;
// from object is going to be replaced with to object and visa vreca
let indexFrom = item.from;
let indexTo = item.to;
let objMovesFrom = itemArray[indexFrom];
let objMovesTo = itemArray[indexTo];
let sortedArray = itemArray;
console.log('Object moves from : ' + objMovesFrom.description);
console.log('Obejct moves to : ' + objMovesTo.description);
sortedArray.map((task, i) => {
if ((i = indexFrom)) {
sortedArray.splice(indexFrom, 1, objMovesTo);
}
if ((i = indexTo)) {
sortedArray.splice(indexTo, 1, objMovesFrom);
}
});
console.log(item);
//dispatch(setTaskList(item.data));
};
I haven't figured to make any sense of it yet...
Thx for the helpful answers!
How about just simply swapping items?..
const dragComplete = item => {
const {
from: sourceIndex,
to: targetIndex,
data: dragList,
} = item;
// // shallow `item.data` copy for a non mutating approach.
// const swapList = Array.from(dragList);
const dragItem = dragList[sourceIndex]; // swapList[sourceIndex];
const swapItem = dragList[targetIndex]; // swapList[targetIndex];
// simply swap items.
// actively mutate `item.data`. // // `item.data` remains unmutated.
dragList[targetIndex] = dragItem; // swapList[targetIndex] = dragItem;
dragList[sourceIndex] = swapItem; // swapList[sourceIndex] = swapItem;
console.log('Object moves from : ' + dragItem.description);
console.log('Object moves to : ' + swapItem.description);
// return swapList;
};
const sample = {
"data": [{
"backgroundColor": "rgb(154, 0, 132)",
"category": "Practical",
"description": "Zero",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.7945943069813785,
"iterations": "",
"key": "0",
}, {
"backgroundColor": "rgb(120, 5, 132)",
"category": "Practical",
"description": "One",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.8857539547977513,
"iterations": "",
"key": "1",
}, {
"backgroundColor": "rgb(184, 10, 132)",
"category": "Practical",
"description": "Two ",
"duedate": {
"cond": false,
"date": "",
},
"id": 0.11232602853449736,
"iterations": "",
"key": "2",
}],
"from": 2,
"to": 1,
};
console.log({ data: sample.data });
dragComplete(sample);
console.log({ data: sample.data });
.as-console-wrapper { min-height: 100%!important; top: 0; }

accessing a json child object not in an array

I'm trying to accessing a json child object which is not in an array. i've tried accessing it with my below script but its not working. i want to be able to access the menuCategory Object
JSON
[
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
]
JAVASCRIPT
callEditMenu(parent, content) {
this.modalService.open(content);
this.editMenuCategoryId = parent.menuCategory.id;
}
May be like
const parent = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
console.log(parent[0].menuCategory.id);
If the parent argument in the callEditMenu function is referring to the JSON you included then try parent[0].menuCategory.id
let arr = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
for (let item of arr) {
if (item.hasOwnProperty("menuCategory")) {
console.log(item["menuCategory"]);
}
};
let res = arr.filter((item) => item && item.menuCategory);
console.log(res[0].menuCategory);
In case you need to find it dynamically. Above are two different ways
Considering there would be multiple items in your array of objects, you can iterate through each object to get the menuCategory name as
let obj = [
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
];
obj.forEach(elem => {
console.log(elem.menuCategory.name);
});

Why does queryAsync() result in added meta data?

I used queryAsync() as prescribed by an answer to a question, and it works, but it adds lots of extra meta data to my query result, which is otherwise a straightforward query.
Here's what I'm using to process/execute the query and log the result:
var retrieveSettings = Promise.method(function (username, connection) {
console.log('User ' + username + ' retrieving settings...');
var q = 'select * from sales_settings';
return connection.queryAsync(q).then(function (rows, fields) {
list = [];
for (x = 0; x < rows.length; x++) {
list.push(rows[x]);
}
//console.log('Settings: ' + JSON.stringify(list, null, 4));
return list;
});
});
and here is the result that is logged:
Settings: [
[
{
"group_name": "add_auto",
"commission_rate": 0,
"monthly_req": 0,
"category_name": "Auto",
"commission_type": "none",
"group_title": "Added Auto"
},
{
"group_name": "add_fire",
"commission_rate": 0,
"monthly_req": 0,
"category_name": "Fire",
"commission_type": "none",
"group_title": "Added Fire"
},
{
"group_name": "bank_dep",
"commission_rate": 25,
"monthly_req": 0,
"category_name": "Bank",
"commission_type": "static",
"group_title": "Bank Deposit"
},
{
"group_name": "bank_loan",
"commission_rate": 75,
"monthly_req": 8,
"category_name": "Bank",
"commission_type": "static",
"group_title": "Bank Loan"
},
{
"group_name": "health",
"commission_rate": 0.084,
"monthly_req": 4,
"category_name": "Health",
"commission_type": "premium",
"group_title": "Health App"
},
{
"group_name": "life",
"commission_rate": 0.084,
"monthly_req": 8,
"category_name": "Life",
"commission_type": "premium",
"group_title": "Life App"
},
{
"group_name": "new_auto",
"commission_rate": 0.03,
"monthly_req": 32,
"category_name": "Auto",
"commission_type": "rate",
"group_title": "Raw New Auto"
},
{
"group_name": "new_fire",
"commission_rate": 0.03,
"monthly_req": 20,
"category_name": "Fire",
"commission_type": "rate",
"group_title": "Raw New Fire"
}
],
[
{
"catalog": "def",
"db": "officeball",
"table": "sales_settings",
"orgTable": "sales_settings",
"name": "group_name",
"orgName": "group_name",
"filler1": [
12
],
"charsetNr": 33,
"length": 135,
"type": 253,
"flags": 20483,
"decimals": 0,
"filler2": [
0,
0
],
"zeroFill": false,
"protocol41": true
},
{
"catalog": "def",
"db": "officeball",
"table": "sales_settings",
"orgTable": "sales_settings",
"name": "commission_rate",
"orgName": "commission_rate",
"filler1": [
12
],
"charsetNr": 63,
"length": 13,
"type": 246,
"flags": 4097,
"decimals": 3,
"filler2": [
0,
0
],
"zeroFill": false,
"protocol41": true
},
{
"catalog": "def",
"db": "officeball",
"table": "sales_settings",
"orgTable": "sales_settings",
"name": "monthly_req",
"orgName": "monthly_req",
"filler1": [
12
],
"charsetNr": 63,
"length": 11,
"type": 3,
"flags": 4097,
"decimals": 0,
"filler2": [
0,
0
],
"zeroFill": false,
"protocol41": true
},
{
"catalog": "def",
"db": "officeball",
"table": "sales_settings",
"orgTable": "sales_settings",
"name": "category_name",
"orgName": "category_name",
"filler1": [
12
],
"charsetNr": 33,
"length": 135,
"type": 253,
"flags": 4097,
"decimals": 0,
"filler2": [
0,
0
],
"zeroFill": false,
"protocol41": true
},
{
"catalog": "def",
"db": "officeball",
"table": "sales_settings",
"orgTable": "sales_settings",
"name": "commission_type",
"orgName": "commission_type",
"filler1": [
12
],
"charsetNr": 33,
"length": 135,
"type": 253,
"flags": 4097,
"decimals": 0,
"filler2": [
0,
0
],
"zeroFill": false,
"protocol41": true
},
{
"catalog": "def",
"db": "officeball",
"table": "sales_settings",
"orgTable": "sales_settings",
"name": "group_title",
"orgName": "group_title",
"filler1": [
12
],
"charsetNr": 33,
"length": 72,
"type": 253,
"flags": 4097,
"decimals": 0,
"filler2": [
0,
0
],
"zeroFill": false,
"protocol41": true
}
]
]
Why is this unusual meta data being added to my query result?
It looks like you are using bluebird, in that case you can use .spread:
var retrieveSettings = Promise.method(function (username, connection) {
console.log('User ' + username + ' retrieving settings...');
var q = 'select * from sales_settings';
return connection.queryAsync(q).spread(function (rows, fields) {
list = [];
for (x = 0; x < rows.length; x++) {
list.push(rows[x]);
}
//console.log('Settings: ' + JSON.stringify(list, null, 4));
return list;
});
});
The problem with the mysql module is that it doesn't conform to the node js callback standard which is (err, result). Instead it uses (err, result1, result2). Because functions can only throw one exception or return one value, bluebird returns an array of [result1, result2] to avoid information loss.
.spread is like .then except it assumes the fulfulliment value is an array and spreads the array's values over the arguments.
The standard callback from mysql's query() returns both a rows and fields. The asynch wrapper you are using (for example if you Q.denodeify()) is only returning a single thing, so for callbacks with multiple parameters it returns an array of [param1,param2] in this case [rows,fields].
Related to this, your function inside the then needs to accept only one parameter (which would be this array of [rows,fields]).
See the second portion of my answer to this question as an illustration.
Your code should thus be something like:
var retrieveSettings = Promise.method(function (username, connection) {
console.log('User ' + username + ' retrieving settings...');
var q = 'select * from sales_settings';
return connection.queryAsync(q).then(function (results) {
var rows = results[0]; // get the rows
var fields = results[1]; // don't really care, but just for illustration
list = [];
for (x = 0; x < rows.length; x++) {
list.push(rows[x]);
}
//console.log('Settings: ' + JSON.stringify(list, null, 4));
return list;
});
});
And actually, for the above code, there's no reason your entire callback can't just be:
return connection.queryAsync(q).then(function (results) {
return results[0]; // get the rows
});

Categories