JSon Parsing not working - javascript

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.

Related

How to send json result as a Dictionary instead of Array in expressjs

I want to send response as a dictionary like this:
{
"id": 5928101,
"category": "animal welfare",
"organizer": "Adam",
"title": "Cat Cabaret",
"description": "Yay felines!",
"location": "Meow Town",
"date": "2019-01-03T21:54:00.000Z",
"time": "2:00",
}
But I am using bellow code, which results an array
var ress = JSON.stringify(sqlResults)
console.log('response json:' + ress)
res.send(ress)
The resulted array has brackets [] like this:
[
{
"id": 5928101,
"category": "animal welfare",
"organizer": "Adam",
"title": "Cat Cabaret",
"description": "Yay felines!",
"location": "Meow Town",
"date": "2019-01-03T21:54:00.000Z",
"time": "2:00",
}
]
How can I send result without a third bracket?
If you return the first element of your sqlResults array you should get the result you wish.
You should also be able to use res.json(dict) to send your result to the client.
sqlResults = [
{
"id": 5928101,
"category": "animal welfare",
"organizer": "Adam",
"title": "Cat Cabaret",
"description": "Yay felines!",
"location": "Meow Town",
"date": "2019-01-03T21:54:00.000Z",
"time": "2:00",
}
];
const dict = sqlResults[0];
var ress = JSON.stringify(dict, null, 2)
console.log('response json:' + ress)
// You can then send using res.send(ress);
// Or simply res.json(dict);

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)

How to access all the matches inside matches array

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

Functional approach to transform an array of objects into a hierarchical structure with aggregates

I'm looking for a functional solution to map this object into a hierarchical structure and group by practice, subjectarea, and asset so that this object:
var data = {
"research": [
{ "practice": "Talent Management", "id": "20992", "title": "Creating a Culture of Leadership", "subjectArea": "Talent Strategy" },
{ "practice": "Talent Management", "id": "20993", "title": "Talent Economics", "subjectArea": "Talent Strategy" },
{ "practice": "Talent Management", "id": "20990", "title": "Finding the Right Talent", "subjectArea": "Recruiting" },
{ "practice": "Human Resources", "id": "20994", "title": "Tips from the Front", "subjectArea": "HR Training" },
{ "practice": "Human Resources", "id": "20995", "title": "Reward Programs", "subjectArea": "Employee Engagement" },
]
}
gets transformed into this (count the number of items for a practice and add the subject areas for the practice as children, count the number of items for a subject area within the practice and add the asset (id and title) as children for the subject area):
{
"name": "research",
"children": [
{
"name": "Talent Management", "size": 3, "children": [
{
"name": "Talent Strategy", "size": 2, "children": [
{ "name": "Creating a Culture of Leadership", "id": "20992", "size": 1 },
{ "name": "Talent Economics", "id": "20993", "size": 1 }
]
},
{
"name": "Recruiting", "size": 1, "children": [
{ "title": "Finding the Right Talent", "id": "20990", "size": 1 },
]
}
]
},
{
"name": "Human Resources", "size": 2, "children": [
{
"name": "HR Training", "size": 1, "children": [
{ "name": "Tips from the Front", "id": "20994", "size": 1 },
]
},
{
"name": "Employee Engagement", "size": 1, "children": [
{ "name": "Reward Programs", "id": "20995", "size": 1 },
]
}
]
},
]
}
I haven't been able to sort out the map and reduce combination to use to yield the correct result with counts, and appreciate any insight.
It might not be what SO is for (as per comments above), but in case anyone needs to transform an array of flat objects into a hierarchical structure that you can simply specify the nesting order, number of levels, and field names, here is a recursive function to do so - https://github.com/lance-p/configurable-transform-flat-array-to-nested. Hope it might be of help to others.

Converting Multidimensional JSON key-value pairs into an Angular Menu (no Angular knowledge required)

I asked this question here:
Working With Dynamic Multidimensional key-value pairs in JSON
But it's become a bit more involved and I can't get where I'm going from that answer. If I have a data object that looks like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
How can I convert that into an Angular menu? The menu would need to list all of the services, and then if the service has an associated item in "fields" that item should be listed underneath it. So for instance "svc1" and its description should be listed on a line (got that working) but then "Product1" and "Product2" with their descriptions should appear on the next two lines because you can see that "svc1" is listed in the "services" field for "Products." Similarly, "svc4" should appear on a line, and then "Wines" and its description on the next line because "svc4" appears in the "services" field of "Wines."
I think the best way is to unpack and re-pack this JSON object in sequential order in the Angular controller and then push this data out to the Angular view but there might be a solution using only the logic available from the view. I've tried a bunch of nested fors and ifs along these lines (very much not working):
var i, j;
var listArray = [];
for (i = 0; i < $scope.svcs.length; i++) {
var littleArray = [$scope.svcs[i].status, $scope.svcs[i].name, $scope.svcs.desc];
listArray.push[littleArray1];
for (j=0; j < $scope.jFA.length; j++) {
if ($scope.jFA[j] == $scope.svcs[i].name) {
if ($scope.jFA[j] == $scope.svcs[i].fields)
littleArray = [$scope.jFA[j].fields] //...etc
}
}
...but that logic just keeps getting more and more dense and isn't working no matter now I try to use it. I liked the simplicity in the answer to the other question but have not had success in replicating it.
So if someone can help me figure out how to get the data into the right sequence using JS I can handle the Angular part. Or if you're an Angular whiz and have an answer along those lines, even better.
So it was a little hard understanding your question, but I gave it my best shot. Does this fiddle show what you are trying to achieve? http://jsfiddle.net/arknr6qz/1/
JS:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope)
{
$scope.checkService = function(service, fieldServices)
{
if (fieldServices.indexOf(service) != -1) return true;
return false;
};
$scope.data = {
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
});
HTML:
<div ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="service in data.custom.services">
{{ service.name }}
<div class="indent" ng-repeat="fields in data.custom.fields">
<span ng-if="checkService(service.name, fields.services)">
{{fields.services.values}}
<span ng-repeat="value in fields.values">
{{value.name}} - {{value.desc}}<br>
</span>
</span>
</div>
</div>
</div>
</div>
and finally css:
.indent {
margin-left:10px;
}

Categories

Resources