JSON Jquery Array Trouble - javascript

How do I get to, Value, Editions, Price, Average?
My non working code:
.append(th.clone().text(value.editions[0].price[1].average))
The JSON layout:
{
"name": "About Face",
"id": "about-face",
"url": "https://api.deckbrew.com/mtg/cards/about-face",
"store_url": "http://store.tcgplayer.com/magic/urzas-legacy/about-face",
"types": [
"instant"
],
"colors": [
"red"
],
"cmc": 1,
"cost": "{R}",
"text": "Switch target creature's power and toughness until end of turn.",
"formats": {
"commander": "legal",
"legacy": "legal",
"vintage": "legal"
},
"editions": [
{
"set": "Urza's Legacy",
"price": {
"low": 89,
"average": 154,
"high": 198
},
"url": "https://api.deckbrew.com/mtg/cards?multiverseid=12414",
}
]
}
My Fiddle can be found here:
http://jsfiddle.net/w2QHz/13/

You should use
.append(th.clone().text(value.editions[0].price.average))
Remove [0] from price, since price is an object not an array.

Related

Is there a way in Vega lite to use different color encodings on a choropleth map, the map has a drop down menu

As stated the map has a drop down menu that changes the display of the map, it selects different columns in the dataset. Ideally I would like to show a different "scheme" for input one and input two or what would also work in my case is to use "reverse" the "scale" encoding to reverse the color scheme for one of the two data columns being loaded
Code extract:
{"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"config": {
"background":"white",
"view": {"stroke": "trasparent"}},
"width": 700,
"height": 500,
"data": {
"url": "https://unpkg.com/world-atlas#1.1.4/world/110m.json",
"format": {
"type": "topojson",
"feature": "countries"}
},
"projection": {
"type": "naturalEarth2"},
"mark": {
"type": "geoshape",
"stroke": "rgb(50, 50, 50)",
"strokeWidth":0.3},
"transform": [
{"calculate":"parseInt(datum.id)", "as":"id_N"},
{
"lookup": "id_N",
"from": {
"key": "id",
"fields": ["alpha3", "name"],
"data": {"url": "data1"}}
},
{"lookup": "alpha3",
"from":{
"data":{
"url":"data2"},
"key": "ISO3",
"fields":["Vulnerability", "Gain"]
}
},
{"calculate": "datum.Vulnerability", "as": "Climate Vulnerability"},
{"calculate": "datum.Gain", "as": "Overall Vulnerability Index"},
{"calculate": "datum[Select]","as": "varSelected"},
],
"params": [
{"name": "Select",
"value": "Vulnerability",
"bind": {
"input": "select",
"options": [
"Climate Vulnerability",
"Overall Vulnerability Index"]}}],
"encoding": {
"color":{
"field":"varSelected",
"type":"quantitative",
"title": null,
"scale":{
"scheme": {"name": "turbo", "count":5}
}
},
"tooltip":[
{"field":"name", "title":"Country"},
{"field":"varSelected","title":"Score","type":"quantitative"}],
}

prepare dataset from json to train RNN in brain.js and node

I have two separate json files that are the response provided from an online api service and will hold the informations about the last two football season of Italian Serie A.
I want to use the unique team id and the result of the match to create a dataset to use with brain.js, what's the best way to achive this?
I've tried to unify the files by copying the content of the second file into the first ove but I will then have two matches array and other duplied fields and I'm not sure on how to process data to ingest into brain.js
{
"filters": {
"season": 2021
},
"resultSet": {
"count": 380,
"first": "2021-08-21",
"last": "2022-05-22",
"played": 380
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"matches": [
{
"area": {
"id": 2114,
"name": "Italy",
"code": "ITA",
"flag": "https://crests.football-data.org/784.svg"
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"season": {
"id": 757,
"startDate": "2021-08-21",
"endDate": "2022-05-22",
"currentMatchday": 38,
"winner": null
},
"id": 333779,
"utcDate": "2021-08-21T16:30:00Z",
"status": "FINISHED",
"matchday": 1,
"stage": "REGULAR_SEASON",
"group": null,
"lastUpdated": "2022-06-25T08:20:15Z",
"homeTeam": {
"id": 108,
"name": "FC Internazionale Milano",
"shortName": "Inter",
"tla": "INT",
"crest": "https://crests.football-data.org/108.png"
},
"awayTeam": {
"id": 107,
"name": "Genoa CFC",
"shortName": "Genoa",
"tla": "GEN",
"crest": "https://crests.football-data.org/107.svg"
},
"score": {
"winner": "HOME_TEAM",
"duration": "REGULAR",
"fullTime": {
"home": 4,
"away": 0
},
"halfTime": {
"home": 2,
"away": 0
}
},
"odds": {
"msg": "Activate Odds-Package in User-Panel to retrieve odds."
},
"referees": [
{
"id": 11336,
"name": "Valerio Marini",
"type": "REFEREE",
"nationality": "Italy"
}
]
},{ ... } //
],
// here I will have the other season
"filters": {
"season": 2020
},
"resultSet": {
"count": 380,
"first": "2021-08-21",
"last": "2022-05-22",
"played": 380
},
"competition": {
"id": 2019,
"name": "Serie A",
"code": "SA",
"type": "LEAGUE",
"emblem": "https://crests.football-data.org/SA.png"
},
"matches": [
{...}]
}
At the momen I've used this code on the json I have created to have training data.
const dataset = Object.values(samples.matches).map( (match) => {
let result
switch( match.score.winner ) {
case 'HOME_TEAM':
result = 0
break;
case 'AWAY_TEAM':
result = 1
break;
case 'DRAW':
result = 2
break;
}
return {
homeTeam: match.homeTeam.id,
awayTeam: match.awayTeam.id,
matchResult: result
}
})
//console.log( dataset )
const trainingData = dataset.map( (data) => {
return {
input: [ data.homeTeam, data.awayTeam ],
output: [ data.matchResult ]
}
})
this is what the data I'm using with brain will look
{ homeTeam: 112, awayTeam: 1106, matchResult: 2 },
{ homeTeam: 472, awayTeam: 113, matchResult: 1 },
{ homeTeam: 584, awayTeam: 98, matchResult: 1 },
{ homeTeam: 99, awayTeam: 107, matchResult: 2 },
{ homeTeam: 471, awayTeam: 1106, matchResult: 0 },
{ homeTeam: 472, awayTeam: 488, matchResult: 0 },
where 0 is when home team win, 1 when away team win and 2 if draw, but I need to have a better solution for handle this case.

How to select some properties from a json result

I am trying to build a simple react app which lists my philips hue bulb name and state(on or off). I have API call which results in the following json. Not sure how to pull bulb name and state.on status.
Here is my json result which gets the list of bulbs connected to my hue bridge. I get this result when i fetch via a the philips hue API.
{
"1": {
"state": {
"on": false,
"bri": 254,
"hue": 50116,
"sat": 248,
"effect": "none",
"xy": [
0.2444,
0.0969
],
"ct": 500,
"alert": "select",
"colormode": "xy",
"mode": "homeautomation",
"reachable": true
},
"swupdate": {
"state": "noupdates",
"lastinstall": "2021-08-19T18:10:44"
},
"type": "Extended color light",
"name": "TV 2",
"modelid": "LCT016",
"manufacturername": "Signify Netherlands B.V.",
"productname": "Hue color lamp",
"capabilities": {
"certified": true,
"control": {
"mindimlevel": 1000,
"maxlumen": 800,
"colorgamuttype": "C",
"colorgamut": [
[
0.6915,
0.3083
],
[
0.1700,
0.7000
],
[
0.1532,
0.0475
]
],
"ct": {
"min": 153,
"max": 500
}
},
"streaming": {
"renderer": true,
"proxy": true
}
},
"config": {
"archetype": "sultanbulb",
"function": "mixed",
"direction": "omnidirectional",
"startup": {
"mode": "safety",
"configured": true
}
},
"uniqueid": "00:17:88:01:03:db:75:df-0b",
"swversion": "1.88.1",
"swconfigid": "47ACF9B2",
"productid": "Philips-LCT016-1-A19ECLv5"
},
"2": {
"state": {
"on": false,
"bri": 254,
"hue": 8417,
"sat": 140,
"effect": "none",
"xy": [
0.4573,
0.4100
],
"ct": 366,
"alert": "select",
"colormode": "ct",
"mode": "homeautomation",
"reachable": true
},
"swupdate": {
"state": "noupdates",
"lastinstall": "2021-08-19T18:10:39"
},
"type": "Extended color light",
"name": "Study",
"modelid": "LCT016",
"manufacturername": "Signify Netherlands B.V.",
"productname": "Hue color lamp",
"capabilities": {
"certified": true,
"control": {
"mindimlevel": 1000,
"maxlumen": 800,
"colorgamuttype": "C",
"colorgamut": [
[
0.6915,
0.3083
],
[
0.1700,
0.7000
],
[
0.1532,
0.0475
]
],
"ct": {
"min": 153,
"max": 500
}
},
"streaming": {
"renderer": true,
"proxy": true
}
},
"config": {
"archetype": "sultanbulb",
"function": "mixed",
"direction": "omnidirectional",
"startup": {
"mode": "safety",
"configured": true
}
},
"uniqueid": "00:17:88:01:03:94:fa:07-0b",
"swversion": "1.88.1",
"swconfigid": "47ACF9B2",
"productid": "Philips-LCT016-1-A19ECLv5"
}
}
You can map them into an array using map(). Since map only works on arrays, and your data is an object, you can use Object.values to return an array of the object's values and use map on that, like this:
const data={1:{state:{on:!1,bri:254,hue:50116,sat:248,effect:"none",xy:[.2444,.0969],ct:500,alert:"select",colormode:"xy",mode:"homeautomation",reachable:!0},swupdate:{state:"noupdates",lastinstall:"2021-08-19T18:10:44"},type:"Extended color light",name:"TV 2",modelid:"LCT016",manufacturername:"Signify Netherlands B.V.",productname:"Hue color lamp",capabilities:{certified:!0,control:{mindimlevel:1e3,maxlumen:800,colorgamuttype:"C",colorgamut:[[.6915,.3083],[.17,.7],[.1532,.0475]],ct:{min:153,max:500}},streaming:{renderer:!0,proxy:!0}},config:{archetype:"sultanbulb",function:"mixed",direction:"omnidirectional",startup:{mode:"safety",configured:!0}},uniqueid:"00:17:88:01:03:db:75:df-0b",swversion:"1.88.1",swconfigid:"47ACF9B2",productid:"Philips-LCT016-1-A19ECLv5"},2:{state:{on:!1,bri:254,hue:8417,sat:140,effect:"none",xy:[.4573,.41],ct:366,alert:"select",colormode:"ct",mode:"homeautomation",reachable:!0},swupdate:{state:"noupdates",lastinstall:"2021-08-19T18:10:39"},type:"Extended color light",name:"Study",modelid:"LCT016",manufacturername:"Signify Netherlands B.V.",productname:"Hue color lamp",capabilities:{certified:!0,control:{mindimlevel:1e3,maxlumen:800,colorgamuttype:"C",colorgamut:[[.6915,.3083],[.17,.7],[.1532,.0475]],ct:{min:153,max:500}},streaming:{renderer:!0,proxy:!0}},config:{archetype:"sultanbulb",function:"mixed",direction:"omnidirectional",startup:{mode:"safety",configured:!0}},uniqueid:"00:17:88:01:03:94:fa:07-0b",swversion:"1.88.1",swconfigid:"47ACF9B2",productid:"Philips-LCT016-1-A19ECLv5"}};
let bulbs = Object.values(data).map(
m=>{return {name: m.name, state: m.state.on}}
);
console.log(bulbs);

Recursively iterate through nested object to deep copy AND apply defaults from separate data source

Ok, this one might be a doozy. I'm banging away but wonder if there's an elegant way to approach this.
I have an object of assets, each of which has some properties, as well as some number of sub-assets in either of two possible objects: assets and characteristics.
I also have a flat object with the defaults for each type of asset stored.
I would like to iterate through the object, detect the type of asset I'm looking at from the ID, load the properties from the flat defaults object, overwrite any of those that's present in the nested object, and return a new nested object that's got all the defaults, but is also updated with anything present in the original nested object.
For example, the nested object:
{
"id": "Bohemian Rhapsody",
"version": "0.10.1.5",
"manifest": "6s43qhuy53as980u08647ugp864q867-08d4svbn9uh54xc8vu",
"slug": "DarkShiftingBolt",
"visibility": "friends",
"locked": true,
"values": {"value0":2},
"assets": [
{
"id": "I see",
"assets": [
{
"id": "a little",
"name": "Queen",
"values": {
"value1": 1,
"value2": 3,
"value3": 2
},
"characteristics": [
{
"id": "silhouetto",
"assets": [
{
"id": "of a man",
"values": {
"value4": 3,
"value5": 1
},
"assets": [
{"id": "Scaramouche"}
]
}
]
}
],
"assets": [
{"id": "Scaramouche"}
]
},
{
"id": "will you",
"name": "Freddy",
"values": {
"value1": 1,
"value2": 0,
"value3": 3
},
"assets": [
{
"id": "do the",
"assets": [
{"id": "fandango"}
]
}
]
}
]
}
]
}
The flat defaults object:
{
"Bohemian Rhapsody": {
"visibility": "hidden",
"locked": false,
"values": {"value0":1},
},
"I see": {
"cost": 4
},
"a little": {
"values": {
"value2": 1,
"value4": 5
},
},
"silhouetto": {
"cost": 1
},
"of a man": {
"genre": "opera"
},
"Scaramouche": {
"rank": 3
},
"will you": {
"values": {
"value4": 0
},
},
"do the": {
"signature": [[4,4],[2,4],[6,8]]
},
"fandango": {
"records": ["thunderbolts","lightning"]
}
}
The desired output object:
{
"id": "Bohemian Rhapsody",
"version": "0.10.1.5",
"manifest": "6s43qhuy53as980u08647ugp864q867-08d4svbn9uh54xc8vu",
"slug": "DarkShiftingBolt",
"visibility": "hidden",
"locked": false,
"values": {"value0":1},
"assets": [
{
"id": "I see",
"cost": 4,
"assets": [
{
"id": "a little",
"name": "Queen",
"values": {
"value1": 1,
"value2": 1,
"value3": 2,
"value4": 5
},
"characteristics": [
{
"id": "silhouetto",
"assets": [
{
"id": "of a man",
"genre": "opera",
"values": {
"value4": 3,
"value5": 1
},
"assets": [
{
"id": "Scaramouche",
"rank": 3
}
]
}
]
}
],
"assets": [
{
"id": "Scaramouche",
"rank": 3
}
]
},
{
"id": "will you",
"name": "Freddy",
"values": {
"value1": 1,
"value2": 0,
"value3": 3,
"value4": 0
},
"assets": [
{
"id": "do the",
"signature": [[4,4],[2,4],[6,8]],
"assets": [
{
"id": "fandango",
"records": ["thunderbolts","lightning"]
}
]
}
]
}
]
}
]
}
What I'm trying is an object.keys recursive function that builds a new object from the properties it finds. I'm curious to know if there's a smarter way to go about it.
Got it thanks to #rayhatfield.
import * as merge from 'deepmerge';
this.manifest = (manifestData as any).default;
this.list = (listData as any).default;
this.list = this.assetIterate(this.list);
assetIterate(asset){
let id = asset.id;
let type = this.manifest.asset_catalog[id].type;
let newAsset = merge.all([this.manifest.asset_taxonomy[type],this.manifest.asset_catalog[id],asset])
Object.keys(asset).forEach((key) => {
if(key === "characteristics" || key === "assets"){
newAsset[key] = [...asset[key]]
newAsset[key].forEach((asset,index) => {
newAsset[key][index] = this.assetIterate(asset);
});
}
});
asset = {...newAsset}
return asset
}
Seems to work for all cases except a corner case in which a sub array needs to have indices replaced instead of concatenated, but I can special-case that when I actually make one of those.

Change JSON format/layout

I have a universal variable on my website which includes line items with relevant details. These line items are reflective of what the user has in their cart. I am integrating with a third party who require the data passed through to them to be formatted slightly different. The below is the data layer currently on my website:
"lineItems": [
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo"
},
"quantity": 1
}
]
The below is what format the third party needs:
"lineItems": [
{
"sku": "s83y016b5",
"name": "Jeans",
"description": "A super great pair of jeans.",
"category": "Everyday Wear",
"other": {"fieldName": "This can be a string or any value you like"}
"unitPrice": 11.99,
"salePrice": 11.99,
"quantity": 2,
"totalPrice": 23.98
"imageUrl": "http://www.my-website.com/a/p/shirt.jpeg",
"productUrl": "http://www.my-website.com/index.php/shirt.html",
}]
Obviously this needs to be dynamic based on the products in the cart. What I intend to do is use javascript to amend the data and send this to the third party via Google Tag Manager.
Any help would be greatly appreciated. Any questions welcome.
This should be close to what you're looking for.
let oldLineItems = "your object";
let newLineItems = {};
newLineItems.lineItems = [];
for (let i in oldLineItems.lineItems) {
newLineItems.lineItems[i] = {};
for (let key in oldLineItems.lineItems[i].product)
{
newLineItems.lineItems[i][key] = oldLineItems.lineItems[i].product[key];
}
}
See code below.
I'm not sure how your lineItems object is set up, but below I just created an array called line Items. If line items is a key in an object which I suspect from your snippet above, you will have to go a level deeper in the for loops used in my example below.
Simply add further details to the new object in the nested for in loops below.
var lineItems =
[
{
"product": {
"id": "s83y016b5",
"sku_code": "s83y016b5",
"url": "/en-gb/jeans/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/shirt.jpeg",
"name": "Jeans",
"manufacturer": "",
"category": "Everyday Wear",
"stock": 116,
"currency": "GBP",
"unit_sale_price": 16,
"unit_price": 16,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 1
},
{
"product": {
"id": "s83y01699",
"sku_code": "s83y01699",
"url": "/en-gb/pants/p/s83y016b5",
"image_url": "http://www.my-website.com/a/p/pants.jpeg",
"name": "Pants",
"manufacturer": "",
"category": "Casual Wear",
"stock": 90,
"currency": "au",
"unit_sale_price": 14,
"unit_price": 14,
"size": "6-9 Months",
"color": "Indigo",
"description": 'Some random description'
},
"quantity": 14
},
];
var newLineItems = [];
for(var char in lineItems){
// Adding some values to newLineItems.
newLineItems.push({
sku: lineItems[char].product.sku_code,
name: lineItems[char].product.name,
description: lineItems[char].product.description,
category: lineItems[char].product.category,
quantity: lineItems[char].quantity
});
}
console.log(JSON.stringify(newLineItems));

Categories

Resources