Related
Have this JSON object in JavaScript that comes from an API:
[
{
"id": 1,
"label": "Breakfast",
"subCategories": [
{
"id": 100,
"label": "Cereals, Muesli",
"items": [
{
"productId": "4fdddf1d-8d31-411d-a908-5edd68a775b7",
"label": "Bircher Muesli"
},
{
"productId": "000673e7-47ec-4dce-a940-ad4aacbd7d73",
"label": "Individual Cereals"
},
{
"productId": "0f739661-5531-4734-9dfd-e145b60667cc",
"label": "Organic Porridge Oats"
}
]
},
{
"id": 101,
"label": "Eggs, Omelettes",
"items": [
{
"productId": "6d608133-ab44-4f9d-ab8e-fc6a3f955397",
"label": "Crushed Avocado with Soughdough Toast"
},
{
"productId": "fcfe91ab-e9b1-4dc0-8c57-ffb9646e0658",
"label": "Crushed Avocado with Crispy Bacon"
},
{
"productId": "2a80e48b-76f6-4bda-abf3-ec8dc7bf1419",
"label": "Crushed Avocado with Smoked Salmon"
},
{
"productId": "ae35e949-abf3-4795-a5df-9af4250c2185",
"label": "Egg White Omelette"
}
]
}
]
},
{
"id": 2,
"label": "Light Lunch",
"subCategories": [
{
"id": 103,
"label": "Condiments",
"items": [
{
"productId": "25503a9b-b553-4b56-a152-49e4121cf4ae",
"label": "Butter"
},
{
"productId": "c1dd9761-f170-4e6a-a7d7-5519a4213874",
"label": "Jam"
}
]
},
{
"id": 104,
"label": "Yoghurts",
"items": [
{
"productId": "938fed24-6d4c-e0cd-8303-0fcd42c87be4",
"label": "Fruit Yoghurt",
},
{
"productId": "62137176-0966-4424-9093-51bd7871d31b",
"label": "Greek Yoghurt",
},
{
"productId": "307e59c4-b103-43d4-988c-75ee539d5d75",
"label": "Granola Parfait: Layers of Berries, Fruit Granola, Yoghurt & Honey",
}
]
}
]
}
]
I need to filter this array above with the search query (Eg: Greek) against the items.label property and have it returned the filtered outcome like below:
[
{
"id": 2,
"label": "Light Lunch",
"subCategories": [
{
"id": 104,
"label": "Yoghurts",
"items": [
{
"productId": "62137176-0966-4424-9093-51bd7871d31b",
"label": "Greek Yoghurt",
}
]
}
]
}
]
I've tried various implementation with filter() with nested some() as seen on StackOverflow but did not return the desired result. Currently this works but only the top level category is filtered and the nested subcategory only exist if there's a match for item.
var searchQuery="Greek";
var data=[]; //JSON omitted for brevity.
var result = data.filter(a=>{
return a.subCategories.some(b=> {
return b.items.some(c=> new RegExp(searchQuery,"i").test(c.label));
});
});
Any help would be greatly appreciated.
You can use Array.reduce for this, iterating first over each of the categories, then each of the subcategories, only adding the subcategory to the output if one of its items contains the search query, and then only adding the category to the output if one of the subcategories contains the search query:
const data = [{
"id": 1,
"label": "Breakfast",
"subCategories": [{
"id": 100,
"label": "Cereals, Muesli",
"items": [{
"productId": "4fdddf1d-8d31-411d-a908-5edd68a775b7",
"label": "Bircher Muesli"
},
{
"productId": "000673e7-47ec-4dce-a940-ad4aacbd7d73",
"label": "Individual Cereals"
},
{
"productId": "0f739661-5531-4734-9dfd-e145b60667cc",
"label": "Organic Porridge Oats"
}
]
},
{
"id": 101,
"label": "Eggs, Omelettes",
"items": [{
"productId": "6d608133-ab44-4f9d-ab8e-fc6a3f955397",
"label": "Crushed Avocado with Soughdough Toast"
},
{
"productId": "fcfe91ab-e9b1-4dc0-8c57-ffb9646e0658",
"label": "Crushed Avocado with Crispy Bacon"
},
{
"productId": "2a80e48b-76f6-4bda-abf3-ec8dc7bf1419",
"label": "Crushed Avocado with Smoked Salmon"
},
{
"productId": "ae35e949-abf3-4795-a5df-9af4250c2185",
"label": "Egg White Omelette"
}
]
}
]
},
{
"id": 2,
"label": "Light Lunch",
"subCategories": [{
"id": 103,
"label": "Condiments",
"items": [{
"productId": "25503a9b-b553-4b56-a152-49e4121cf4ae",
"label": "Butter"
},
{
"productId": "c1dd9761-f170-4e6a-a7d7-5519a4213874",
"label": "Jam"
}
]
},
{
"id": 104,
"label": "Yoghurts",
"items": [{
"productId": "938fed24-6d4c-e0cd-8303-0fcd42c87be4",
"label": "Fruit Yoghurt",
},
{
"productId": "62137176-0966-4424-9093-51bd7871d31b",
"label": "Greek Yoghurt",
},
{
"productId": "307e59c4-b103-43d4-988c-75ee539d5d75",
"label": "Granola Parfait: Layers of Berries, Fruit Granola, Yoghurt & Honey",
}
]
}
]
}
];
const searchQuery = "Greek";
const regex = new RegExp(searchQuery, "i");
const result = data.reduce((cats, cat) => {
cat.subCategories = cat.subCategories.reduce((subs, sub) => {
sub.items = sub.items.filter(item => regex.test(item.label));
if (sub.items.length) subs.push(sub);
return subs;
}, []);
if (cat.subCategories.length) cats.push(cat);
return cats;
}, []);
console.log(result);
Here I have a working example which returns your requested output:
function finder(data, query) {
for(let i in data) {
// return the item if the label contains the search query
if(new RegExp(query,"i").test(data[i].label)) return data[i]
// go deeper in subCategories if exist
if(data[i].subCategories) {
let sub = finder(data[i].subCategories, query)
if(sub) {
data[i].subCategories = [sub]
return data[i]
}
// go deeper in items if exist
} else if(data[i].items){
let item = finder(data[i].items, query)
if(item) {
data[i].items = [item]
return data[i]
}
}
}
// didn't find the search query in this branch
return false
}
console.log(finder(data, 'Greek'))
with data your input data
Currently I've got the following JSON feed:
var data = {
"feeds": {
"regions": [{
"name": "Lichtenberg",
"id": "01408.b",
"suburbs": [{
"name": "Fennpfuhl",
"views": 76400
},
{
"name": "Lichtenberg",
"views": 87895
},
{
"name": "Rummelsberg",
"views": 10239
}
]
},
{
"name": "Mitte",
"id": "03442.f",
"suburbs": [{
"name": "Tiergarten",
"views": 82695
},
{
"name": "Mitte",
"views": 67234
},
{
"name": "Hansaviertel",
"views": 10848
},
{
"name": "Moabit",
"views": 67500
}
]
},
{
"name": "Friedrichshain-Kreuzberg",
"id": "01991.o",
"suburbs": [{
"name": "Friedrichshain",
"views": "98494"
},
{
"name": "Kreuzberg",
"views": "27800"
}
]
},
{
"name": "Templehof-Schöneberg",
"id": "01778.k",
"suburbs": [{
"name": "Friedenau",
"views": 76595
},
{
"name": "Schöneberg",
"views": 20731
},
{
"name": "Templehof",
"views": 58000
},
{
"name": "Mariendorf",
"views": 32300
}
]
},
{
"name": "Pankow",
"id": "02761.q",
"suburbs": [{
"name": "Wießensee",
"views": 81294
},
{
"name": "Prenzlauer Berg",
"views": 76470
},
{
"name": "Pankow",
"views": 90210
}
]
}
],
}
};
Effectively I want to do two things:
Loop through the Regions to get the 4 names
Loop through all the views in each region, sum them up, and return them as values under the 4 names.
Here's a sample of the output that I just quickly typed up:
var viewsPerRegion =
[{
label: "Litchtenberg",
total: 174534
}, {
label: "Mitte",
total: 228277
}, {
label: "Friedrichshain-Kreuzberg",
total: 126294
}, {
label: "Templehof-Schöneberg",
total: 187626
}];
etc...
I do want to note that data.feeds.region[2].suburbs.views is stored as a string, so that's something I'll need to change into an integer first.
Anyway the solution I have so far (which doesn't really work) is as follows:
var viewsPerRegion, i, j, x;
for (i in data.feeds.regions) {
x += data.feeds.regions[i].name;
for (j in data.feeds.regions[i].suburbs.views){
x += data.feeds.regions[i].suburbs.views[j];
}
}
viewsPerRegion = x;
Any help is certainly appreciated - bit of a newbie in JSON and javascript.
You can map the regions array, extracting the name from each, and get the total by using reduce to add up each of the views:
const data={"feeds":{"regions":[{"name":"Lichtenberg","id":"01408.b","suburbs":[{"name":"Fennpfuhl","views":76400},{"name":"Lichtenberg","views":87895},{"name":"Rummelsberg","views":10239}]},{"name":"Mitte","id":"03442.f","suburbs":[{"name":"Tiergarten","views":82695},{"name":"Mitte","views":67234},{"name":"Hansaviertel","views":10848},{"name":"Moabit","views":67500}]},{"name":"Friedrichshain-Kreuzberg","id":"01991.o","suburbs":[{"name":"Friedrichshain","views":"98494"},{"name":"Kreuzberg","views":"27800"}]},{"name":"Templehof-Schöneberg","id":"01778.k","suburbs":[{"name":"Friedenau","views":76595},{"name":"Schöneberg","views":20731},{"name":"Templehof","views":58000},{"name":"Mariendorf","views":32300}]},{"name":"Pankow","id":"02761.q","suburbs":[{"name":"Wießensee","views":81294},{"name":"Prenzlauer Berg","views":76470},{"name":"Pankow","views":90210}]}],}}
const viewsPerRegion = data.feeds.regions.map(({ name, suburbs }) => ({
label: name,
total: suburbs.reduce((a, { views }) => a + Number(views), 0)
}));
console.log(viewsPerRegion);
I'm very new to Javascript and have been given a task. I have a JSON feed that has been given as follows:
var data = {
"feeds": {
"regions": [{
"name": "Lichtenberg",
"id": "01408.b",
"suburbs": [{
"name": "Fennpfuhl",
"views": 76400
},
{
"name": "Lichtenberg",
"views": 87895
},
{
"name": "Rummelsberg",
"views": 10239
}
]
},
{
"name": "Mitte",
"id": "03442.f",
"suburbs": [{
"name": "Tiergarten",
"views": 82695
},
{
"name": "Mitte",
"views": 67234
},
{
"name": "Hansaviertel",
"views": 10848
},
{
"name": "Moabit",
"views": 67500
}
]
},
{
"name": "Friedrichshain-Kreuzberg",
"id": "01991.o",
"suburbs": [{
"name": "Friedrichshain",
"views": "98494"
},
{
"name": "Kreuzberg",
"views": "27800"
}
]
},
{
"name": "Templehof-Schöneberg",
"id": "01778.k",
"suburbs": [{
"name": "Friedenau",
"views": 76595
},
{
"name": "Schöneberg",
"views": 20731
},
{
"name": "Templehof",
"views": 58000
},
{
"name": "Mariendorf",
"views": 32300
}
]
},
{
"name": "Pankow",
"id": "02761.q",
"suburbs": [{
"name": "Wießensee",
"views": 81294
},
{
"name": "Prenzlauer Berg",
"views": 76470
},
{
"name": "Pankow",
"views": 90210
}
]
}
],
"branding": [{
"municipality_id": "01408.b",
"brand_color": "#f9cd90"
}, {
"municipality_id": "03442.f",
"brand_color": "#F28123"
}, {
"municipality_id": "01991.o",
"brand_color": "#D34E24"
}, {
"municipality_id": "01778.k",
"brand_color": "#563F1B"
}, {
"municipality_id": "02761.q",
"brand_color": "#38726C"
}],
"customer": {
"name": "Viktoria Tiedemann",
"date_of_birth": "1981-09-19",
"address": {
"street": "Schönfließer Str 9",
"suburb": "Prenzlauer Berg",
"postcode": "10439"
}
}
}
};
The task is simple - to find the suburb and the region of Viktoria Tiedemann. So far I've tried using the below:
var customer_suburb;
var customer_name = 'Viktoria Tiedemann';
for (var i = 0; i < data.feeds.customer.length; i++){
if (data.feeds.customer.name[i] == customer_name){
customer_suburb = data.feeds.customer.address.suburb;
}
}
but it keeps on returning undefined values - where am I going wrong? I'm thinking to use the same process to get the region.
In your data, you have just one customer — not an array of customers — which is accessible with:
data.feeds.customer
( if customer was supposed to be an array, you could find Viktoria with : let customer = data.feeds.customer.find(c => c.name === 'Viktoria Tiedemann') )
You can get the suburb with:
let suburb = data.feeds.customer.address.suburb
Once you have that, you just need to find() the region whose suburbs array has this. For that find() combined with some() does this succinctly:
var data = {"feeds": {"regions": [{"name": "Lichtenberg","id": "01408.b","suburbs": [{ "name": "Fennpfuhl", "views": 76400 },{ "name": "Lichtenberg", "views": 87895 },{ "name": "Rummelsberg", "views": 10239 }]},{"name": "Mitte","id": "03442.f","suburbs": [{ "name": "Tiergarten", "views": 82695 },{ "name": "Mitte", "views": 67234 },{ "name": "Hansaviertel", "views": 10848 },{ "name": "Moabit", "views": 67500 }]},{"name": "Friedrichshain-Kreuzberg","id": "01991.o","suburbs": [{ "name": "Friedrichshain", "views": "98494" },{ "name": "Kreuzberg", "views": "27800" }]},{"name": "Templehof-Schöneberg","id": "01778.k", "suburbs": [{ "name": "Friedenau", "views": 76595 },{ "name": "Schöneberg", "views": 20731 },{ "name": "Templehof", "views": 58000 },{ "name": "Mariendorf", "views": 32300 }]},{"name": "Pankow","id": "02761.q","suburbs": [{ "name": "Wießensee", "views": 81294 },{ "name": "Prenzlauer Berg", "views": 76470 },{ "name": "Pankow", "views": 90210 }]}],"branding": [{"municipality_id": "01408.b","brand_color": "#f9cd90"},{"municipality_id": "03442.f","brand_color": "#F28123"},{"municipality_id": "01991.o","brand_color": "#D34E24"},{"municipality_id": "01778.k","brand_color": "#563F1B"},{"municipality_id": "02761.q","brand_color": "#38726C"}],"customer": {"name": "Viktoria Tiedemann","date_of_birth": "1981-09-19","address": {"street": "Schönfließer Str 9","suburb": "Prenzlauer Berg","postcode": "10439"}}}};
let suburb = data.feeds.customer.address.suburb
let region = data.feeds.regions.find(region => region.suburbs.some(s => s.name === suburb))
console.log("suburb:", suburb, "region:", region.name)
{
"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);
}
}
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.