Related
I've been playing around trying to learn in an API project using Postman and conducting tests using JavaScript. So far, I have succeeded with the help of reading on websites and watching YouTube videos. Of course, previous tests and playing around have been fairly easy but now I came to a stop. I really tried to figure this out for several weeks but I need further guidance, a push in the right direction or direct help.
What I'm trying to do is to filter out some of the response to only view objects that contain specific data.
To do that, I'm using a filter where I want all products containing a specific value inside an array "product_option_values".
My first approach was to see if I could sort products having any values from the first array, and it worked. It filters just fine.
var filterSmall = jsonData.products.filter(fs => fs.associations.product_option_values);
My next approach was to get to my goal of filtering out products according to specific values inside this array. I tried many simple .(dot) combinations and pointing to [index] to access it without any luck. (I must add that I know how to access this from a specific product, but that way doesn't work when filtering).
I've also tried other approaches such as:
var filterSmall = jsonData.products.filter(fs => fs.associations["product_option_values", 0, "name"] === "S");
and other similar combinations.
This is a very shortened sample of the structure of "products" which in its full form consists of 20 products and far more values inside of it:
{
"products": [
{
"id": 16,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Mountain fox notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "22"
},
{
"id": "23"
}
]
}
},
{
"id": 17,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Brown bear notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "23"
},
{
"id": "24"
}
]
}
}
]
}
and here is a small and expanded sample from product_option_values:
{
"product_option_values": [
{
"id": 1,
"id_attribute_group": "1",
"color": "",
"position": "0",
"name": "S"
},
{
"id": 2,
"id_attribute_group": "1",
"color": "",
"position": "1",
"name": "M"
},
{
"id": 3,
"id_attribute_group": "1",
"color": "",
"position": "2",
"name": "L"
}
]
}
How do I proceed? Did I do anything correct or even close to it?
Perhaps I've been staring at this for too long.
Thanks in advance.
If you want to compare nested attributes you have to transform the objects (e.g. by using a map operation), so that the relevant attributes are easily accessible for a comparison. If you want to filter by product_option_value id, you could do something like this:
const jsonData = {
"products": [
{
"id": 16,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Mountain fox notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "22"
},
{
"id": "23"
}
]
}
},
{
"id": 17,
"manufacturer_name": "Graphic Corner",
"quantity": "0",
"price": "12.900000",
"indexed": "1",
"name": "Brown bear notebook",
"associations": {
"categories": [
{
"id": "2"
},
{
"id": "6"
}
],
"product_option_values": [
{
"id": "23"
},
{
"id": "24"
}
]
}
}
]
};
const sample = {
"product_option_values": [
{
"id": 22,
"id_attribute_group": "1",
"color": "",
"position": "0",
"name": "S"
},
{
"id": 2,
"id_attribute_group": "1",
"color": "",
"position": "1",
"name": "M"
},
{
"id": 3,
"id_attribute_group": "1",
"color": "",
"position": "2",
"name": "L"
}
]
};
const ids = sample.product_option_values.map((el) => String(el.id));
console.log(ids);
const filtered = jsonData.products.filter((fs) => fs.associations.product_option_values.map((e) => e.id).some((f) => ids.includes(f)));
console.log(filtered);
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
})))
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))
{
"name": "English Premier League 2015/16",
"rounds": [
{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
{
"date": "2015-08-08",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
{
"date": "2015-08-08",
"team1": {
"key": "bournemouth",
"name": "Bournemouth",
"code": "BOU"
},
"team2": {
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-08",
"team1": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"team2": {
"key": "watford",
"name": "Watford",
"code": "WAT"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"team2": {
"key": "sunderland",
"name": "Sunderland",
"code": "SUN"
},
"score1": 4,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "norwich",
"name": "Norwich",
"code": "NOR"
},
"team2": {
"key": "crystalpalace",
"name": "Crystal Palace",
"code": "CRY"
},
"score1": 1,
"score2": 3
},
{
"date": "2015-08-08",
"team1": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
"team2": {
"key": "westham",
"name": "West Ham United",
"code": "WHU"
},
"score1": 0,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "newcastle",
"name": "Newcastle United",
"code": "NEW"
},
"team2": {
"key": "southampton",
"name": "Southampton",
"code": "SOU"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "liverpool",
"name": "Liverpool",
"code": "LIV"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-10",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 0,
"score2": 3
}
]
}
]
}
I want to log all the matches which are inside matches array . But i can't seem to access them because there are objects ,arrays ,more arrays and more objects nested inside one another. Kinda confused.please help explaining how to access elements in such situation. Which loops to use, what to do in case of looping through objects and so on. Hope I have explained my problem quite elaborately.
You can try this this code here:
const data = {"name":"English Premier League 2015/16","rounds":[{"name":"Play-Off um 1 Premierleague-Platz:","matches":[{"date":"2015-08-08","team1":{"key":"manutd","name":"Manchester United","code":"MUN"},"team2":{"key":"tottenham","name":"Tottenham Hotspur","code":"TOT"},"score1":1,"score2":0},{"date":"2015-08-08","team1":{"key":"bournemouth","name":"Bournemouth","code":"BOU"},"team2":{"key":"astonvilla","name":"Aston Villa","code":"AVL"},"score1":0,"score2":1},{"date":"2015-08-08","team1":{"key":"everton","name":"Everton","code":"EVE"},"team2":{"key":"watford","name":"Watford","code":"WAT"},"score1":2,"score2":2},{"date":"2015-08-08","team1":{"key":"leicester","name":"Leicester City","code":"LEI"},"team2":{"key":"sunderland","name":"Sunderland","code":"SUN"},"score1":4,"score2":2},{"date":"2015-08-08","team1":{"key":"norwich","name":"Norwich","code":"NOR"},"team2":{"key":"crystalpalace","name":"Crystal Palace","code":"CRY"},"score1":1,"score2":3},{"date":"2015-08-08","team1":{"key":"chelsea","name":"Chelsea","code":"CHE"},"team2":{"key":"swansea","name":"Swansea","code":"SWA"},"score1":2,"score2":2},{"date":"2015-08-09","team1":{"key":"arsenal","name":"Arsenal","code":"ARS"},"team2":{"key":"westham","name":"West Ham United","code":"WHU"},"score1":0,"score2":2},{"date":"2015-08-09","team1":{"key":"newcastle","name":"Newcastle United","code":"NEW"},"team2":{"key":"southampton","name":"Southampton","code":"SOU"},"score1":2,"score2":2},{"date":"2015-08-09","team1":{"key":"stoke","name":"Stoke City","code":"STK"},"team2":{"key":"liverpool","name":"Liverpool","code":"LIV"},"score1":0,"score2":1},{"date":"2015-08-10","team1":{"key":"westbrom","name":"West Bromwich Albion","code":"WBA"},"team2":{"key":"mancity","name":"Manchester City","code":"MCI"},"score1":0,"score2":3}]}]};
data.rounds.forEach((round) => {
round.matches.forEach((match) => {
console.log(`Results ${ match.score1 } | ${ match.score2 }`);
})
});
Basically you're using a mixture of array and object references.
You use your object references (data.rounds or round.matches) to get to specific properties on your object. Then you can you array functions (.forEach() which you can read about here) to access the objects in each array. Then you just access the properties of those sub objects.
Hope this helps.
Building on Phil's comment, something like this should help you iterate through the matches and do something with each.
obj.rounds[0].matches.forEach(match => {
console.log(match);
})
The snippet shared is actually a object. Inside this object there is a key by name rounds, which is again array of objects.
So data.rounds will give the value which is an array.
Inside this array there is array of matches. But data.rounds is array of only one object. Hence data.rounds[0] will allow to access it's value. [0] being the index, since in array the first element is at 0 index & data.rounds[0].matches will give the array of matches
var data = {
"name": "English Premier League 2015/16",
"rounds": [{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
//other objects
]
}
console.log(data.rounds[0].matches)
DEMO
I guest that your data is structured in a JSON that you are going to decoded using the json_decode function like this:
$myMatches = json_decode($yourJSON);
After that JSON gets converted into an object you can access any property by following the following rules:
Every opening curly bracket on the JSON gets converted into an object, and you will have to use the arrow syntax like this: $myMatches->attribute
For example, imagine an object "$person" with the following structure:
{
"name": "manutd",
"lastname": "Manchester United",
"phone": "MUN"
}
To print the name you will have to do:
echo $person->name;
On the other hand, every normal bracket gets transformed into an array and you have to use brackets to access that information (like any other array), like this: $myMatches['attribute']
For example that same person but now with array syntax:
[
"name": "manutd",
"lastname": "Manchester United",
"phone": "MUN"
]
To print the name you will have to do:
echo $person['name'];
Now, for your question in particular
That said, if you want to print the date of the first round of the first match, you will have to do:
echo $myMatches->rounds[0]->matches[0]->date;
I have prepared this functions for your disposal:
//This function returns all the matches in one tournament round
function getMatchesOfRound($myMatches, $roundNumber)
{
return $myMatches->rounds[$roundNumber]->matches;
}
//This function returns all the matches played by $teamKey
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if($match->team1->key == $teamKey || $match->team2->key == $teamKey) $matches[] = $match;
return $matches;
}
//this function determines the winner of a given match and returns the $teamKey
function getWinerFromMatch($match){
if($match->score1 > $match->score2) return $match->team1;
else if($match->score1 < $match->score2) return $match->team2;
else return null;
}
//This function returns all matches won by $teamKey
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if(getWinerFromMatch($match) == $teamKey) $matches[] = $match;
return $matches;
}
//This function returns all ties
function getAllMatchesOfTeam($myMatches, $teamKey){
$matches = [];
foreach($myMatches->rounds as $rounds)
foreach($rounds->matches as $match)
if(getWinerFromMatch($match) == null) $matches[] = $match;
return $matches;
}
You get the idea, I hope this helps. I have not tested the code, maybe it has minor sytax errors.
result = {
"name": "English Premier League 2015/16",
"rounds": [
{
"name": "Play-Off um 1 Premierleague-Platz:",
"matches": [
{
"date": "2015-08-08",
"team1": {
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2": {
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
{
"date": "2015-08-08",
"team1": {
"key": "bournemouth",
"name": "Bournemouth",
"code": "BOU"
},
"team2": {
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-08",
"team1": {
"key": "everton",
"name": "Everton",
"code": "EVE"
},
"team2": {
"key": "watford",
"name": "Watford",
"code": "WAT"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "leicester",
"name": "Leicester City",
"code": "LEI"
},
"team2": {
"key": "sunderland",
"name": "Sunderland",
"code": "SUN"
},
"score1": 4,
"score2": 2
},
{
"date": "2015-08-08",
"team1": {
"key": "norwich",
"name": "Norwich",
"code": "NOR"
},
"team2": {
"key": "crystalpalace",
"name": "Crystal Palace",
"code": "CRY"
},
"score1": 1,
"score2": 3
},
{
"date": "2015-08-08",
"team1": {
"key": "chelsea",
"name": "Chelsea",
"code": "CHE"
},
"team2": {
"key": "swansea",
"name": "Swansea",
"code": "SWA"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "arsenal",
"name": "Arsenal",
"code": "ARS"
},
"team2": {
"key": "westham",
"name": "West Ham United",
"code": "WHU"
},
"score1": 0,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "newcastle",
"name": "Newcastle United",
"code": "NEW"
},
"team2": {
"key": "southampton",
"name": "Southampton",
"code": "SOU"
},
"score1": 2,
"score2": 2
},
{
"date": "2015-08-09",
"team1": {
"key": "stoke",
"name": "Stoke City",
"code": "STK"
},
"team2": {
"key": "liverpool",
"name": "Liverpool",
"code": "LIV"
},
"score1": 0,
"score2": 1
},
{
"date": "2015-08-10",
"team1": {
"key": "westbrom",
"name": "West Bromwich Albion",
"code": "WBA"
},
"team2": {
"key": "mancity",
"name": "Manchester City",
"code": "MCI"
},
"score1": 0,
"score2": 3
}
]
}
]
};
for ( let i=0, totalRounds = result.rounds.length; i < totalRounds; i++) {
let round = result.rounds[i];
console.log( round.name );
for ( let j=0, totalMatches = round.matches.length; j < totalMatches; j++ ) {
let match = round.matches[j];
console.log( match.date + ': ' + match.team1.name + " " + match.score1 + " - " + match.team2.name + " " + match.score2)
}
}
You can fetch all the matches in a variable then iterate over it using any loop.
If there is only 1 round then this will do the task.
var matches = object.rounds[0]. matches;
for(var match in matches){
console.log(match);
}
If there more rounds then you to first iterate over rounds and inside that loop fetch all the matches in that particular round.
for(var round in object.rounds){
var matches = round.matches;
for(var prop in matches){
console.log(prop);
}
}
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 */ }