How to access all the matches inside matches array - javascript

{
"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);
}
}

Related

Javascript - Multiple nested filter expressions

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

Lookup Value in JSON using Javascript

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)

Node + Json validate key nested array

I have sample json. In that json I need to check the following things.
Valid Json or not.
Name key is required without empty(list name and item name).
items array length need to greater than 5.
I attached my code and its not working. I feel this approach is not good. Can anyone please suggest to me the correct path.
var test = '{ "lists": [ { "items": [ { "name": "Curd0", "sequence": 3 }, { "name": "Curd1", "sequence": 2 }, { "name": "Curd2", "sequence": 1 }, { "name": "Curd3", "sequence": 4 }, { "name": "Curd4", "sequence": 10 }, { "name": "Curd5", "sequence": 9 }, { "name": "Curd6", "sequence": 8 }, { "name": "Curd7", "sequence": 7 }, { "name": "Curd8", "sequence": 6 }, { "name": "Curd9", "sequence": 5 } ], "name": "Curd Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:18:26.169Z" }, { "items": [ { "name": "Milk0", "sequence": 3 }, { "name": "Milk1", "sequence": 2 }, { "name": "Milk2", "sequence": 1 }, { "name": "Milk3", "sequence": 4 }, { "name": "Milk4", "sequence": 10 }, { "name": "Milk5", "sequence": 9 }, { "name": "Milk6", "sequence": 8 } ], "name": "Milk Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:18:44.504Z" }, { "items": [ { "name": "Water0", "sequence": 3 }, { "name": "Water1", "sequence": 2 }, { "name": "Water2", "sequence": 1 }, { "name": "Water3", "sequence": 4 }, { "name": "Water4", "sequence": 10 }, { "name": "Water5", "sequence": 9 }, { "name": "Water6", "sequence": 8 } ], "name": "Water Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:19:02.329Z" }, { "items": [ { "name": "Fruit0", "sequence": 3 }, { "name": "Fruit1", "sequence": 2 }, { "name": "Fruit2", "sequence": 1 }, { "name": "Fruit3", "sequence": 4 } ], "name": "Fruit Family", "status": "new", "created_by": 100036, "created_on": "2016-05-05T13:19:15.503Z" } ] }';
function Validate(data, callback) {
for (index in lists) {
if (!lists.index.hasOwnProperty('name')) {
callback("Name cannot be empty");
}
var itemList = lists.index.items;
if (itemList.length < 5) {
callback("List need more than 5 lenth");
}
for ( i = 0; i < itemList.length; i++) {
if (!itemList[i].hasOwnProperty('name')) {
callback("Item Name cannot be empty");
}
}
}
callback(null);
}
Validate(test, function (err) {
console.log(err);
});
every is probably what you need :
function containsNameInLists(element) {
return element.hasOwnProperty('name');
}
function containsNameInItems(element) {
return element.items.every(containsKeyName);
}
function containsKeyName(element) {
return element.hasOwnProperty('name');
}
function lengthSuperiorTo5(element) {
return element.length > 5;
}
function itemsArrayLength(){
return element.items.every(lengthSuperiorTo5);
}
You can test if your string is a valid JSON string simply using JSON.parse
Try to play with the string to test different functions.
Demo
EDIT : I've added the additionnal functions :
EDIT DEMO
The callback will call multiple times, please add a "return":
return callback(...);
For validate json in node.js, there is a good library: https://github.com/hapijs/joi

Adding extra values in json object

For Example
I have Object named tempobj and below are tempobj[0] and tempobj[1] sample data.
I want to add extra info like name and status this object
tempobj ["info"]["name"] = "title";
tempobj ["info"]["id"] = "23243";
But when i do stringify , Jquery is ignoring this value...how can i add data like this to this kind of structure.
[
[{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
}, {
"name": "snack ",
"value": "pecan pie butter",
"check": 0
}, {
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}],
[{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
}, {
"name": "snack ",
"value": "Smoked Salmon nori roll "
}, {
"name": "dessert",
"value": "Apple muffins"
}]
tempobj is an array ([]).
When you try to set some values with:
tempobj["info"]["name"] = "title";
tempobj["info"]["id"] = "23243";
you treat it like an object ({}).
If you want to add some data to your tempobj, you have to change its structure like this for example:
{
"info": {
"name": "title",
"id": "23243"
},
"items": [
[{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
}, {
"name": "snack ",
"value": "pecan pie butter",
"check": 0
}, {
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}],
[{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
}, {
"name": "snack ",
"value": "Smoked Salmon nori roll "
}, {
"name": "dessert",
"value": "Apple muffins"
}]
]
}
Here is a sample:
var tempobj = {
items: [
[{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
}, {
"name": "snack ",
"value": "pecan pie butter",
"check": 0
}, {
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}],
[{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
}, {
"name": "snack ",
"value": "Smoked Salmon nori roll "
}, {
"name": "dessert",
"value": "Apple muffins"
}]
]
}
tempobj.info = {
name: 'title',
id: '23243'
};
// Another way:
//tempobj.info = {};
//tempobj.info.name = 'title';
//tempobj.info.id = '23243';
console.log(JSON.stringify(tempobj));
It sounds like you're doing something like this:
// Create an array
var a = [];
// Add an entry to it
a[0] = "I'm an array entry";
// Add a non-entry property to it
a.foo = "bar";
// Convert to JSON
var json = JSON.stringify(a);
...and finding that the string doesn't have the foo property.
That's correct. JSON's arrays don't support arbitrary non-entry properties the way JavaScript's arrays do, and so they get silently dropped during serialization (the same way properties with the value undefined or referring to functions do).
The answer is not to do that if you need to go through JSON.
But, the structure you quoted later in your question doesn't do that, and can readily be created like this:
var data = [
[
{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
},
{
"name": "snack ",
"value": "pecan pie butter",
"check": 0
},
{
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
}
],
[
{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
},
{
"name": "snack ",
"value": "Smoked Salmon nori roll "
},
{
"name": "dessert",
"value": "Apple muffins"
}
]
];
var json = JSON.stringify(data);
That structure is (from the outside in): An array containing two entries, each of which is another array; within each array, you have a series of objects, which have properties.
I don't know why you want to have the two arrays inside the outermost array, but that's what the structure showed.
If you meant just a single array, that would look like this if you were creating it all at once:
var data = [
{
"name": "Breakfast",
"value": "buffalo strip ",
"check": 0
},
{
"name": "snack ",
"value": "pecan pie butter",
"check": 0
},
{
"name": "dessert",
"value": "chocolate zucchani brownie",
"check": 0
},
{
"name": "Breakfast",
"value": "Stir Fried Kale and Baccon ",
"check": 1
},
{
"name": "snack ",
"value": "Smoked Salmon nori roll "
},
{
"name": "dessert",
"value": "Apple muffins"
}
];
var json = JSON.stringify(data);
...or if building it up over time:
var data = [];
data.push({
name: "Breakfast",
value: "buffalo strip ",
check: 0
});
data.push({
name: "snack ",
value: "pecan pie butter",
check: 0
});
// ...
var json = JSON.stringify(data);

JSon Parsing not working

I am trying to parse JSON data from the flixter API to import it to my blog.
In the example below, I tried using JavaScript to output the cast info for the movie expendables.
My full goal would be to get it to output the information
"Sylvester Stallone as Barney Ross, Jason Statham as Lee Christmas" and so on.
Here is my jsFiddle http://jsfiddle.net/k3V9p/3/
var jsontext = '{
"cast": [{
"id": "162664630",
"name": "Sylvester Stallone",
"characters": ["Barney Ross"]
}, {
"id": "162653720",
"name": "Jason Statham",
"characters": ["Lee Christmas"]
}, {
"id": "162652223",
"name": "Jet Li",
"characters": ["Yin Yang"]
}, {
"id": "162664307",
"name": "Dolph Lundgren",
"characters": ["Gunnar Jensen"]
}, {
"id": "162670654",
"name": "Chuck Norris",
"characters": ["Booker"]
}, {
"id": "326392465",
"name": "Terry Crews",
"characters": ["Hale Caesar"]
}, {
"id": "770731413",
"name": "Randy Couture",
"characters": ["Toll Road"]
}, {
"id": "770833479",
"name": "Liam Hemsworth",
"characters": ["Billy the Kid"]
}, {
"id": "770704326",
"name": "Scott Adkins",
"characters": ["Hector"]
}, {
"id": "770670020",
"name": "Nan Yu",
"characters": ["Maggie"]
}, {
"id": "162670708",
"name": "Jean-Claude Van Damme",
"characters": ["Jean Vilain"]
}, {
"id": "162652509",
"name": "Bruce Willis",
"characters": ["Mr. Church"]
}, {
"id": "162662233",
"name": "Arnold Schwarzenegger",
"characters": ["Trench"]
}, {
"id": "489251774",
"name": "Amanda Ooms",
"characters": ["Pilar"]
}, {
"id": "377608335",
"name": "Charisma Carpenter",
"characters": ["Lacy"]
}, {
"id": "771417014",
"name": "Nikolette Noel",
"characters": ["Sophia"]
}],
"links": {
"rel": "http://api.rottentomatoes.com/api/public/v1.0/movies/771238417.json"
}
}';
var titles = JSON.parse(jsontext);
document.write(titles.cast);
The problem you have is with end of lines in your string literal. You can write them like this :
var jsontext = '{\
"cast": [{\
But in your case, it's not clear if you really need JSON, as you could directly create your object as
var titles = {
cast": [{
...
I would say that the first problem you have is the JSON.parsing (which dystroy has perfectly answered), after solving that you will have to deal with rendering which you could do like this: (demo)
var titles = {
"cast": [{
"id": "162664630", "name": "Sylvester Stallone", "characters": ["Barney Ross"]
}, {"id": "162653720", "name": "Jason Statham", "characters": ["Lee Christmas"]
}, {"id": "162652223", "name": "Jet Li", "characters": ["Yin Yang"]
}, {"id": "162664307", "name": "Dolph Lundgren", "characters": ["Gunnar Jensen"]
}, {"id": "162670654", "name": "Chuck Norris", "characters": ["Booker"]
}, {"id": "326392465", "name": "Terry Crews", "characters": ["Hale Caesar"]
}, {"id": "770731413", "name": "Randy Couture", "characters": ["Toll Road"]
}, {"id": "770833479", "name": "Liam Hemsworth", "characters": ["Billy the Kid"]
}, {"id": "770704326", "name": "Scott Adkins", "characters": ["Hector"]
}, {"id": "770670020", "name": "Nan Yu", "characters": ["Maggie"]
}, {"id": "162670708", "name": "Jean-Claude Van Damme", "characters": ["Jean Vilain"]
}, {"id": "162652509", "name": "Bruce Willis", "characters": ["Mr. Church"]
}, {"id": "162662233", "name": "Arnold Schwarzenegger", "characters": ["Trench"]
}, {"id": "489251774", "name": "Amanda Ooms", "characters": ["Pilar"]
}, {"id": "377608335", "name": "Charisma Carpenter", "characters": ["Lacy"]
}, {"id": "771417014", "name": "Nikolette Noel", "characters": ["Sophia"]
}],
"links": {
"rel": "http://api.rottentomatoes.com/api/public/v1.0/movies/771238417.json"
}
},
star,
staring = [];
for (star = 0; star < titles.cast.length; star++) {
staring.push(titles.cast[star].name + ' as ' + titles.cast[star].characters[0]);
}
document.getElementById('Credits').innerHTML = staring.join(', ');
You don't need to change what flixster api is returning to you.
The problem is you need to call the API directly... do not copy&paste the result.
See the usage here http://developer.rottentomatoes.com/docs/read/json/v10/examples
Just do the Ajax call and onSuccess (searchCallback in the example) you will have the data parsed in json already.

Categories

Resources