Complex JSON structure with JS - javascript

I'm looking for a way to generate an HTML table from a JSON data.
I'm limitated with tooling options because we use CMS, so I can only use JS, JQuery and ApacheVelocity (without making new templates, only using the 'syntax').
Well, I get this kind of JSON data from remote API:
{
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
The first problem I face are those numeric indexes.
The only way to make reference to this is like this:
arr_from_json.data.data.region[123].game[11844220].team1_name
It is ok if we only have a few "games" extracted, even 100 games. But it is impossible to keep it updated with thousands of games who are constantly being updated.
Is there some way for iterarte through this ugly JSON structure?
Many thanks
Edit:
I want to create a table with the distinct games:
Zorya Luhansk - SC Braga
W1 X W2
2.39 3.01 2.82
Most important data/keys to me are: both team names, name of the possible outcome and price.

You can convert those indexed objects into traditional arrays using a helper function, then iterate over the data in a more natural way after transforming it. See below for an example using Array.map and the helper function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
const resp = {
"code": 0,
"rid": "0",
"data": {
"subid": "-7766883411351472375",
"data": {
"region": {
"123": {
"alias": "Europe",
"game": {
"11811809": {
"id": 11811809,
"team1_name": "Zorya Luhansk",
"team2_name": "SC Braga",
"market": {
"188597332": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566458": {
"price": 2.39,
"name": "W1"
},
"624566459": {
"price": 3.01,
"name": "X"
},
"624566460": {
"price": 2.82,
"name": "W2"
}
}
}
}
},
"11811810": {
"id": 11811810,
"team1_name": "Olympiacos Piraeus",
"team2_name": "FC Luzern",
"market": {
"188597340": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"624566476": {
"price": 1.34,
"name": "W1"
},
"624566477": {
"price": 4.29,
"name": "X"
},
"624566478": {
"price": 7.92,
"name": "W2"
}
}
}
}
},
"11844220": {
"id": 11844220,
"team1_name": "NK Domzale",
"team2_name": "FC Ufa",
"market": {
"189338624": {
"type": "P1XP2",
"name": "Ganador del Partido",
"event": {
"626913821": {
"price": 2.35,
"name": "W1"
},
"626913822": {
"price": 2.86,
"name": "X"
},
"626913823": {
"price": 3.03,
"name": "W2"
}
}
}
}
}
}
}
}
}
}
}
function keysToArray(obj){ return Object.keys(obj).map(key => obj[key]); }
function parseGameData(data){
return keysToArray(data.region).map(obj => keysToArray(obj.game).map(obj => {
obj.market = keysToArray(obj.market).map(obj => {
return {
name: obj.name,
event: keysToArray(obj.event)
}
})
return obj
}))
}
console.log(parseGameData(resp.data.data))

Related

How to change object values with another object key path?

How to change the destination values with source object key path?
The source object is like below
{
"total-info": [{
"emp-sal-info": {
"id": "emp01",
"currency": "dollar",
"details": {
"sal-details": [{
"name": "peter",
"income": "$400"
},
{
"name": "peter wife",
"income": "$500"
}
]
}
}
}, {
"emp-sal-info": {
"id": "emp01",
"currency": "dollar",
"details": {
"sal-details": [{
"name": "John",
"income": "$900"
},
{
"name": "John wife",
"income": "$400"
}
]
}
}
}]
}
The destination is like this:
{
"company": [{
"Peter": {
"id": "emp01",
"sal": "$3000"
}
}, {
"John": {
"id": "emp02",
"sal": "$5000"
}
}]
}
Then how do I change the destination object to the below format?
{
"company": [{
"Peter": {
"id": "emp01",
"sal": "['total-info']['0']['emp-sal-info']['details']['sal-details']['0']['salary']+['total-info']['0']['emp-sal-info']['details']['sal-details']['0']['salary']"
}
}, {
"John": {
"id": "emp02",
"sal": "['total-info']['1']['emp-sal-info']['details']['sal-details']['0']['salary']+['total-info']['1']['emp-sal-info']['details']['sal-details']['0']['salary']"
}
}]
}
Can you please tell me how transform to arrays like above. Thanks you

What is the most efficient way to convert this JavaScript object of objects to a more useful structure?

For example, I currently have a few objects that output to:
{
"location": {
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
}
{
"location": {
"category": "Data_Set_2",
"categoryID": "2ec5e0c1-b839-59a6-8fd5-b09468d6cdd7"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
}
{
"location": {
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
}
{
"location": {
"category": "Data_Set_3",
"categoryID": "b905ae3d-1a41-5659-b15e-f305588a0afa"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
}
Basically I have a 13 different data sets (ex: Data_Set_1, Data_Set_2, etc.) that appear somewhat randomly and more than once in this large set of multiple repeated objects. Each data set has around 6000 data entry points (dataEntryNumber: 0010, dataEntryNumber 0016, etc.).
How would I parse through this data to fit the format of:
{
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
data: {
"0001": {
"value": 1.42343432,
"timestamp": "null"
}
"0002": {
"value: 1.424234255,
"timestamp": "null"
etc... etc...
}
etc... etc...
}
{
"category": "Data_Set_2",
"categoryID": "2ec5e0c1-b839-59a6-8fd5-b09468d6cdd7"
data: {
"0001": {
"value": 9.42343432,
"timestamp": "null"
}
"0002": {
"value: 13.424234255,
"timestamp": "null"
etc... etc...
}
etc... etc...
}
etc... etc...
I'm aware that this is probably not proper JSON formatting so any help would be great! Only the portion that says "data" needs to be in JSON. The rest can remain however it is.
I wrote a library called blinq (modelled on Microsoft's Linq-to-Objects) that provides a number of useful transformations over iterable sequences. It is very well suited to this kind of transformation.
The transformation can be done as follows:
const query = blinq(data)
.groupBy(item => item.location.categoryID)
.select(g => ({
...g.first().location,
data: g.aggregate({}, (prev, item) => ({
...prev,
[item.data_objects.dataEntryNumber]: item.data_objects.data
}))
}))
const output = [...query]
console.log(output)
See below for a working example.
const {
blinq
} = window.blinq
const data = [{
"location": {
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
},
{
"location": {
"category": "Data_Set_2",
"categoryID": "2ec5e0c1-b839-59a6-8fd5-b09468d6cdd7"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
},
{
"location": {
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
},
{
"location": {
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
},
"data_objects": {
"dataEntryNumber": "0011",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
},
{
"location": {
"category": "Data_Set_3",
"categoryID": "b905ae3d-1a41-5659-b15e-f305588a0afa"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
}
]
const query = blinq(data)
.groupBy(item => item.location.categoryID)
.select(g => ({
...g.first().location,
data: g.aggregate({}, (prev, item) => ({
...prev,
[item.data_objects.dataEntryNumber]: item.data_objects.data
}))
}))
const output = [...query]
console.log(output)
<script src="https://cdn.jsdelivr.net/npm/blinq"></script>
It looks like you want to refine your objects. You can do so using map, and assigning the desired keys to the desired values:
var arr = [{
"location": {
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
},
{
"location": {
"category": "Data_Set_2",
"categoryID": "2ec5e0c1-b839-59a6-8fd5-b09468d6cdd7"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
},
{
"location": {
"category": "Data_Set_1",
"categoryID": "66e711cb-81ad-5e22-9fc7-910283924442"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
},
{
"location": {
"category": "Data_Set_3",
"categoryID": "b905ae3d-1a41-5659-b15e-f305588a0afa"
},
"data_objects": {
"dataEntryNumber": "0010",
"data": {
"value": 1.4593582153320312,
"timestamp": "null"
}
}
}]
console.log(arr.map(({location, data_objects: d}) => ({
data: {
[d.dataEntryNumber]: {...d.data}
},
...location
})))

How can I merge duplicate keys in a JavaScript object?

I have a JavaScript object as follows :
{
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
}
]
}, {
"$origin": "domainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
I want to merge duplicate key in "$origin" and append value in "a" key
{
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
},
{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
I know how to merge duplicate keys from two different object from other topics, but I don't know how to merge and find duplicate keys in the same object.
First of all, use reduce to collect the duplicates and save them in a temporary object with values of $origin as its keys. Then iterate the keys and reconstruct the the object.
Another way would be doing most of the work in the reduce method with some filtering but I think my current solution is faster.
const data = {
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
}
]
}, {
"$origin": "domainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
},
{
"$origin": "eomainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
const result = { zone: [] }
const tmp = data.zone.reduce((acc, curr) => {
if (acc.hasOwnProperty(curr.$origin)) {
acc[curr.$origin] = acc[curr.$origin].concat(curr.a)
} else {
acc[curr.$origin] = curr.a
}
return acc;
}, {})
result.zone = Object.keys(tmp).map((key) => {
return {
$origin: key,
a: tmp[key]
}
})
console.log(result)
You can loop through the array starting from index 1 and keep on pushing the values in the object at index 0
let x = {
"zone": [{
"$origin": "domainname.com.",
"a": [{
"name": "ironman",
"ip": "192.168.0.1"
}, {
"name": "thor",
"ip": "192.168.0.2"
},
{
"name": "odin",
"ip": "192.168.0.3"
}
]
}, {
"$origin": "domainname.com.",
"a": [{
"name": "javis",
"ip": "192.168.0.4"
},
{
"name": "jump",
"ip": "192.168.0.5"
},
{
"name": "jupiter",
"ip": "192.168.0.6"
}
]
}]
}
// starting to loop from index 1, new elements will be pushed
to the object at index 0
for (var i = 1; i < x.zone.length; i++) {
// looping through the array of object at index 1 ...
x.zone[i].a.forEach(function(item) {
// dummy object which will have values from other objects
let dumObj = {};
dumObj.name = item.name;
dumObj.ip = item.ip;
x.zone[0].a.push(dumObj);
})
}
console.log(x)

Javascript marge and slice json

Based on this array json I need to merge it constantly.
Using push() I get this kind of result
JSON
**0:**{
"net_drops.vpn0": {
"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}
},
"named_local.view_resolver_numfetch__default": {
"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}
}
}
**1:**{
"net_drops.vpn0": {
"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}
},
"named_local.view_resolver_numfetch__default": {
"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}
}
}
...
But I need this kind of result
JSON
{
"net_drops.vpn0": {
**0:**{"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}},
**1:**{"name":"net_drops.vpn0",
"context":"net.drops",
"units":"drops/s",
"last_updated": 1501806176,
"dimensions": {
"inbound": {
"name": "inbound",
"value": 0.0000000
},
"outbound": {
"name": "outbound",
"value": 0.0000000
}
}}
},
"named_local.view_resolver_numfetch__default": {
**0:**{"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}},
**1:**{"name":"named_local.view_resolver_numfetch__default",
"context":"named.resolver_active_queries",
"units":"queries",
"last_updated": 1501806176,
"dimensions": {
"queries": {
"name": "queries",
"value": 0.0000000
}
}}
}
...
}
It's possible? If yes how can I do it?
Then I need to slice the objects based on last_update, if the last_update is older than 30 minutes of current time is sliced
Eg: current time 10:00:00, object last_update 09:31:00 is sliced.
It's possible? If yes how can I do it?
Best regards
Looks like you are combining the data with the same key.
To achieve that result, loop through the original JSON data and push it to another array by key. In your case the keys are: 'net_drops.vpn0' and 'named_local.view_resolver_numfetch__default' like: array.net_drops.vpn0 = json_data
For the slicing based on the 'last_updated' key, you can try to use array.filter function. Check this LINK for reference.

mapping 2-D array in react-native

Attached JSON:-
[
{
"category":"Faces",
"items": [
{
"name": "Oh well!",
"art" : "¯\\_(ツ)_/¯"
},
{
"name": "Disapproving Look",
"art": "ಠ_ಠ"
},
{
"name": "Disapproving Look 2",
"art": "ఠ_ఠ"
},
{
"name": "Glasses Smile",
"art": "ʘ‿ʘ"
},
{
"name": "Devious Smile",
"art": "ಠ‿ಠ"
},
{
"name": "Frowning",
"art": "ಠ╭╮ಠ"
},
{
"name": "Yelling",
"art": "ಠoಠ"
},
{
"name": "Mustache Man",
"art": "ಠ▃ಠ"
},
{
"name": "Blank Stare",
"art": "ರ_ರ"
},
{
"name": "HUH?",
"art": "ლ(`ー´ლ)"
},
{
"name": "Rosy Cheeks",
"art": "(。◕‿◕。)"
},
{
"name": "hehehe",
"art": "( ¬‿¬)"
},
{
"name": "Pointing Out",
"art": "☜(⌒▽⌒)☞"
},
{
"name": "Haha!",
"art": "☜(゚ヮ゚☜)"
},
{
"name": "Run Away Crying",
"art": "ε=ε=ε=┌(;*´Д`)ノ"
},
{
"name": "Cheers",
"art": "( ^_^)o自自o(^_^ )"
},
{
"name": "Up All Night",
"art": "۞_۞"
},
{
"name": "High",
"art": "q(❂‿❂)p"
},
{
"name": "Dazed & Confused",
"art": "⊙﹏⊙"
},
{
"name": "No Clue!",
"art": "¯\\_(⊙︿⊙)_/¯"
},
{
"name": "I Dunno",
"art": "¯\\(°_o)/¯ "
},
{
"name": "Staring Eyes",
"art": "Ꙭ"
},
{
"name": "Cat Eyes",
"art": "ф_ф"
},
{
"name": "Winking",
"art": "◕‿↼"
},
{
"name": "Reaching Down",
"art": "(,,Ծ‸Ծ,,)"
},
{
"name": "Just Woke up",
"art": "╰(´・`)ノ"
},
{
"name": "Sleep Walking",
"art": "(¬º-°)¬"
},
{
"name": "Disappointed Look",
"art": "(-_-)"
}
]
},
{
"category": "Emotions",
"items": [
{
"name": "Angry",
"art": "{{|└(>o< )┘|}}"
},
{
"name": "Why, God, WHY!?",
"art": "щ(゚Д゚щ)"
},
{
"name": "In Love",
"art": "♥(。✿‿✿。)❤"
},
{
"name": "In Love 2",
"art": "♥‿♥"
},
{
"name": "Puzzled",
"art": "く(^_・)ゝ"
},
{
"name": "Mad",
"art": "( ゚Д゚)"
},
{
"name": "Whatever",
"art": "(^~^)ノ"
},
{
"name": "Happy",
"art": "ヽ(´▽`)/"
},
{
"name": "Love at First Sight",
"art": "꒰♡ˊ͈ ु꒳ ूˋ͈꒱.⑅*♡"
},
{
"name": "Need A Hug",
"art": "ヽ(´ー`)ノ"
},
{
"name": "So Beautiful!",
"art": "ಥ_ಥ"
},
{
"name": "Sad / Crying",
"art": "ಥ﹏ಥ"
},
{
"name": "Embarrased",
"art": "(﹡⌒▽⌒﹡)"
},
{
"name": "Extra Embarrased",
"art": "(/ω\)"
},
{
"name": "No Thanks",
"art": "(ღ˘⌣˘ღ)"
},
{
"name": "I've Seen The Light",
"art": "•✞_✞•"
}
]
},]
Attempt in React-Native
class Textables extends Component{
constructor(){
super()
this.state={data:[]}
}
getData(){
return fetch('https://raw.githubusercontent.com/OTGApps/Textables/master/resources/content.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount(){
this.getData();
}
render()
{
let articles= this.state.data.map(function(articleData, index){
let articles1 = articleData.map(function(meow, j){
return(<content>
<Card><CardItem><Body>
<Text>{meow.items.name}</Text></Body></CardItem></Card>
<Card><CardItem><Body>
<Text>{meow.items.art}</Text></Body></CardItem></Card></content>
);
});
return(
<Card><CardItem><Body>
<Text>{articleData.category}</Text></Body></CardItem></Card>
);
});
return(
<Content>
{articles}
</Content>
)
}
}
Error:- undefined is not a function (evaluating 'articleData.map')
I'm trying to map the the items one by one by looping through each array.
Should I use index.map instead of articleData.map?
articleData points to the object in the data array. It looks like:
{
"category": "Emotions",
"items": [],
}
You want to use articleData.items.map.
Additionally, that getData function will probably not work how you want. Since it's not bound to the class scope, it won't be able to access this.setState. You'll probably want to either add this to your constructor:
this.getData = this.getData.bind(this)
or, you can change the function declaration:
getData = () => { /* your function */ }

Categories

Resources