reduce & sum array of objects entries - javascript

From the following array:
var arr = [{ "Year": 2019, "Title": "Sample1", "Sum": 1020000.0, "Budget":0},
{ "Year": 2019, "Title": "Sample2", "Sum": 2546658.0, "Budget":100},
{ "Year": 2019, "Title": "Sample3", "Sum": 1020000.0, "Budget":1000},
{ "Year": 2020, "Title": "Sample1", "Sum": 3472000.0, "Budget":100},
{ "Year": 2020, "Title": "Sample2", "Sum": 1020000.0, "Budget":10},
{ "Year": 2020, "Title": "Sample3", "Sum": 2452000.0, "Budget":50},
{ "Year": 2021, "Title": "Sample1", "Sum": 1000.0, "Budget":100},
{ "Year": 2021, "Title": "Sample2", "Sum": 119000.0, "Budget":10},
{ "Year": 2021, "Title": "Sample3", "Sum": 234000.0, "Budget":50}]
]
I need to change this into a single year per row, were the value of each "Title" has an entry with its "Sum" value and the Budget values should be aggregated together ie.
[{ "Year": 2019, "Sample1": 1020000.0, "Sample2":2546658.0, "Sample3":1020000.0 , "Budget":1100},{ etc]
My platform does not support ES6, through answers from an earlier post I have used .reduce as follows to get most of the way:
var res = arr.reduce(function(acc, curr) {
acc[curr.Year] = acc[curr.Year];
acc[curr.Year] = acc[curr.Year] || { Year: curr.Year } ;
acc[curr.Year][curr.Title] = curr.Sum;
return acc;
res = Object.keys(res).map(function(key) {
return res[key];
});
This produces:
[{ "Year": 2019, "Sample1": 1020000.0, "Sample2":2546658.0, "Sample3":1020000.0 },
{ "Year": 2020, "Sample2": 3472000.0, "Sample2":1020000.0, "Sample3":2452000.0},
{ "Year": 2021, "Sample3": 1000.0, "Sample2":119000.0, "Sample3":234000.0}]
But I cannot find a way to also sum the Budget figures together and add it to the same entry. I suspect I need to perform a separate reduce function on a duplicate array and push the result into the res array using the forEach loop with Year as the key. Can anyone see a way of doing this in the same reduce function?

When initializing a Year object in the reduce callback, also initialize a Budget property to 0. Then, on each iteration for that year, add to the budget property in addition to setting the Sample property:
var arr = [{ "Year": 2019, "Title": "Sample1", "Sum": 1020000.0, "Budget":0},
{ "Year": 2019, "Title": "Sample2", "Sum": 2546658.0, "Budget":100},
{ "Year": 2019, "Title": "Sample3", "Sum": 1020000.0, "Budget":1000},
{ "Year": 2020, "Title": "Sample1", "Sum": 3472000.0, "Budget":100},
{ "Year": 2020, "Title": "Sample2", "Sum": 1020000.0, "Budget":10},
{ "Year": 2020, "Title": "Sample3", "Sum": 2452000.0, "Budget":50},
{ "Year": 2021, "Title": "Sample1", "Sum": 1000.0, "Budget":100},
{ "Year": 2021, "Title": "Sample2", "Sum": 119000.0, "Budget":10},
{ "Year": 2021, "Title": "Sample3", "Sum": 234000.0, "Budget":50}
]
var res = arr.reduce(function(acc, curr) {
acc[curr.Year] = acc[curr.Year] || { Year: curr.Year, Budget: 0 } ;
// ^^^^^^^^^
acc[curr.Year][curr.Title] = curr.Sum;
acc[curr.Year].Budget += curr.Budget;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return acc;
}, {});
var output = Object.keys(res).map(function(key) {
return res[key];
});
console.log(output);
Note that the line in your original code
acc[curr.Year] = acc[curr.Year];
doesn't accomplish anything at all - you may omit it entirely.
You could consider using Babel and polyfills, allowing you to write code in the latest and greatest version of the language, while preserving compatibility for obsolete browsers, in which case, the code could be prettified to:
var arr=[{"Year":2019,"Title":"Sample1","Sum":1020000.0,"Budget":0},{"Year":2019,"Title":"Sample2","Sum":2546658.0,"Budget":100},{"Year":2019,"Title":"Sample3","Sum":1020000.0,"Budget":1000},{"Year":2020,"Title":"Sample1","Sum":3472000.0,"Budget":100},{"Year":2020,"Title":"Sample2","Sum":1020000.0,"Budget":10},{"Year":2020,"Title":"Sample3","Sum":2452000.0,"Budget":50},{"Year":2021,"Title":"Sample1","Sum":1000.0,"Budget":100},{"Year":2021,"Title":"Sample2","Sum":119000.0,"Budget":10},{"Year":2021,"Title":"Sample3","Sum":234000.0,"Budget":50}]
const output = Object.values(arr.reduce((a, { Year, Title, Sum, Budget }) => {
a[Year] = a[Year] || { Year, Budget: 0 };
a[Year][Title] = Sum;
a[Year].Budget += Budget;
return a;
}, {}));
console.log(output);

Related

Transform array of data into grouped data for SectionList component

I'll freely admit that Javascript is not my strongest language, and React Native is very new, so, there may be an obviously easy way to do this that I'm not seeing.
I've got an API that presents some transaction data in a simple structure:
[
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
},
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
},
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
]
I want to present this data using a SectionList component, with the transactions in sections by date. My (likely crude) attempt to solve this was going to be to transform this data into the following structure:
[
{
"date": "2021-09-10",
"transactions": [
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
}
]
},
{
"date": "2021-09-09",
"transactions": [
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
}
]
},
{
"date": "2021-09-07",
"transactions": [
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
]
}
]
But I'm honestly lost as to how to transform this data (or if there's a better way to solve this problem). I started by using Lodash's groupBy function, which seemed promising, but it looks like SectionList doesn't want an object, it wants an array.
Transforming the output of groupBy into an array straight off drops the keys and I've got grouped data but no clear value for the section header.
Again, there's probably some deviously simple way to address this, data comes in as a flat array all the time. I appreciate any guidance, assistance, or examples anybody can point me to.
const input = [
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
},
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
},
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
]
const result = input.reduce((accum, current)=> {
let dateGroup = accum.find(x => x.date === current.date);
if(!dateGroup) {
dateGroup = { date: current.date, transactions: [] }
accum.push(dateGroup);
}
dateGroup.transactions.push(current);
return accum;
}, []);
console.log(result)
Given an array, whenever your result is expecting to have same number of elements, use map, but since your result has different number of elements, use reduce as shown above. The idea is by having reduce, loop over each element, see if you can find the element, and push the current element into the list
The lodash groupBy just helps you with group data, you should process grouped data by converting it into your format.
const input = [
{
"id": 1,
"title": "Apple Store",
"date": "2021-09-10",
"amount": "$100.00",
},
{
"id": 41,
"title": "Zulauf, Walter and Metz",
"date": "2021-09-10",
"amount": "$14.00",
},
{
"id": 9,
"title": "Aufderhar PLC",
"date": "2021-09-09",
"amount": "$78.00",
},
{
"id": 10,
"title": "Bayer and Sons",
"date": "2021-09-07",
"amount": "$67.00",
}
];
const groupedArray = _.groupBy(input, "date");
let result = [];
for (const [key, value] of Object.entries(groupedArray)) {
result.push({
'date': key,
'transactions': value
})
}
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
simply
const data =
[ { id: 1, title: 'Apple Store', date: '2021-09-10', amount: '$100.00' }
, { id: 41, title: 'Zulauf, Walter and Metz', date: '2021-09-10', amount: '$14.00' }
, { id: 9, title: 'Aufderhar PLC', date: '2021-09-09', amount: '$78.00' }
, { id: 10, title: 'Bayer and Sons', date: '2021-09-07', amount: '$67.00' }
]
const res = Object.entries(data.reduce((r,{id,title,date,amount})=>
{
r[date] = r[date] ?? []
r[date].push({id,title,date,amount})
return r
},{})).map(([k,v])=>({date:k,transactions:v}))
console.log( res )
.as-console-wrapper { max-height: 100% !important; top: 0 }
With lodash you can group by the date then map to the required form:
const input = [{"id":1,"title":"Apple Store","date":"2021-09-10","amount":"$100.00"},{"id":41,"title":"Zulauf, Walter and Metz","date":"2021-09-10","amount":"$14.00"},{"id":9,"title":"Aufderhar PLC","date":"2021-09-09","amount":"$78.00"},{"id":10,"title":"Bayer and Sons","date":"2021-09-07","amount":"$67.00"}];
const result = _.map(
_.groupBy(input, 'date'),
(transactions, date) => ({ date, transactions })
)
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
you could use loadash
var result = _(data)
.groupBy(item => item.date)
.map((value, key) => ({date: key, transactions: value}))
.value();

How to transform an array/dataset in javascript? [duplicate]

This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 3 years ago.
Say I have an array of music
The code below returns all the titles for all genres. However, I only want the title names for songs in the Country genre.
const music= [{
"title": "Cheats",
"year": 2018,
"cast": ["Jane Rhee", "Kacey Brown"],
"genres": ["Country"]
}, {
"title": "Road",
"year": 2018,
"cast": ["Jeff Bates", "Alan Walker", "Cindy Bates"],
"genres": ["Country"]
}, {
"title": "Trail Down",
"year": 2018,
"cast": ["Ken Clemont"],
"genres": ["Jazz"]
}, {
"title": "Way Down",
"year": 2018,
"cast": ["Denzel Harr", "Dan Smith", "Lee Kyle", "Nate Hill"],
"genres": ["Pop"]
}, {
"title": "Fountain",
"year": 2018,
"cast": ["Brad Smith", "Rosa King"],
"genres": ["Rock"]
}, {
"title": "Gold Bells",
"year": 2018,
"cast": ["Paisley John"],
"genres": ["Blues"]
}, {
"title": "Mountain Curve",
"year": 2018,
"cast": ["Michael Johnson"],
"genres": ["Country"]
}, {
"title": "Arabella",
"year": 2018,
"cast": [],
"genres": ["Jazz"]
}, {
"title": "Curved",
"year": 2018,
"cast": ["Brett Shay"],
"genres": ["Country"]
}];
let songs = [];
for (var i = 0; i < music.length; i++) {
songs.push(music[i].title);
}
console.log(songs);
.filter the array by whether Country is included in the genres, then .map to the titles:
const music=[{title:"Cheats",year:2018,cast:["Jane Rhee","Kacey Brown"],genres:["Country"]},{title:"Road",year:2018,cast:["Jeff Bates","Alan Walker","Cindy Bates"],genres:["Country"]},{title:"Trail Down",year:2018,cast:["Ken Clemont"],genres:["Jazz"]},{title:"Way Down",year:2018,cast:["Denzel Harr","Dan Smith","Lee Kyle","Nate Hill"],genres:["Pop"]},{title:"Fountain",year:2018,cast:["Brad Smith","Rosa King"],genres:["Rock"]},{title:"Gold Bells",year:2018,cast:["Paisley John"],genres:["Blues"]},{title:"Mountain Curve",year:2018,cast:["Michael Johnson"],genres:["Country"]},{title:"Arabella",year:2018,cast:[],genres:["Jazz"]},{title:"Curved",year:2018,cast:["Brett Shay"],genres:["Country"]}];
const countryTitles = music
.filter(({ genres }) => genres.includes('Country'))
.map(({ title }) => title);
console.log(countryTitles)
If you want to do it while only iterating over the dataset once, use reduce instead:
const music=[{title:"Cheats",year:2018,cast:["Jane Rhee","Kacey Brown"],genres:["Country"]},{title:"Road",year:2018,cast:["Jeff Bates","Alan Walker","Cindy Bates"],genres:["Country"]},{title:"Trail Down",year:2018,cast:["Ken Clemont"],genres:["Jazz"]},{title:"Way Down",year:2018,cast:["Denzel Harr","Dan Smith","Lee Kyle","Nate Hill"],genres:["Pop"]},{title:"Fountain",year:2018,cast:["Brad Smith","Rosa King"],genres:["Rock"]},{title:"Gold Bells",year:2018,cast:["Paisley John"],genres:["Blues"]},{title:"Mountain Curve",year:2018,cast:["Michael Johnson"],genres:["Country"]},{title:"Arabella",year:2018,cast:[],genres:["Jazz"]},{title:"Curved",year:2018,cast:["Brett Shay"],genres:["Country"]}];
const countryTitles = music
.reduce((a, { genres, title }) => {
if (genres.includes('Country')) {
a.push(title)
}
return a;
}, []);
console.log(countryTitles)
Try this:
let songs = [];
for (var i = 0; i < music.length; i++) {
if(music[i].genres == "Country"){ // if music genres equal to "country"
songs.push(music[i].title);
}
}
// output : Cheats,Road,Mountain Curve,Curved

Convert Array into an Object with Arrays [duplicate]

This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Closed 3 years ago.
I'm trying to create a navigational menu out of some data. In order to do this I need to manipulate the data into an object of arrays. I am attempting to do this using map(), I've gotten to the point of making the keys of the object and a corresponding value, however, I don't know how to handle the multiple titles under it's corresponding year. Any help would be greatly appreciated.
const data = [
{
"fields": {
"title": "Frozen Thorns",
"year": 2017,
}
},
{
"fields": {
"title": "The Professional Years",
"year": 2018,
}
},
{
"fields": {
"title": "Green Nothing",
"year": 2018,
}
},
{
"fields": {
"title": "The Next Voyage",
"year": 2018,
}
},
{
"fields": {
"title": "Smooth Sorcerer",
"year": 2019,
}
},
{
"fields": {
"title": "Azure Star",
"year": 2019,
}
}]
const menu = Object.assign({}, ...data.map(item => ({[item.fields.year]: item.fields.title})));
// OUTPUT
// {
// 2017: "Frozen Thorns",
// 2018: "The Next Voyage",
// 2019: "Azure Star"
// }
// DESIRED OUTPUT
// {
// 2017: ["Frozen Thorns"],
// 2018: ["The Professional Years", "Green Nothing", "The Next Voyage"],
// 2019: ["Smooth Sorcerer", "Azure Star"]
// }
The general rule is that if you want to keep the same shape as your original array, then you use map, but if you want to turn it into a smaller shape you use the appropriately named reduce. Take a look at this.
const data = [
{
"fields": {
"title": "Frozen Thorns",
"year": 2017,
}
},
{
"fields": {
"title": "The Professional Years",
"year": 2018,
}
},
{
"fields": {
"title": "Green Nothing",
"year": 2018,
}
},
{
"fields": {
"title": "The Next Voyage",
"year": 2018,
}
},
{
"fields": {
"title": "Smooth Sorcerer",
"year": 2019,
}
},
{
"fields": {
"title": "Azure Star",
"year": 2019,
}
}];
const menu = data.reduce((accumulator, currentValue) => {
accumulator[currentValue.fields.year] = (accumulator[currentValue.fields.year] || []).concat(currentValue.fields.title);
return accumulator;
}, {});
console.log(menu);

Adding elements to array inside for.. in

I'm trying to make a 2 dimensional array with a json data. The first array is made within a for in loop and is pushed to the top-level array after. I tried to print the array and I got same value for each elements which is the last data from the json.
json:
[
{
"startYear": 2014,
"startMonth": 6,
"startDay": 31,
"endYear": 2014,
"endMonth": 7,
"endDay": 29,
"selectedDate": "2014_7_8",
"departureStation": "Manila",
"arrivalStation": "Boracay (Caticlan)",
"departureStationCode": "(MNL)",
"arrivalStationCode": "(MPH)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_0_2014_6_31": {
"containerId": "date_0_2014_6_31",
"fromLabel": "From",
"currency": "PHP",
"price": null,
"formattedDate": "Thu, Jul 31, 2014", //data to get
"year": "2014",
"month": "6",
"day": "31",
"points": null,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_0_2014_7_1": {
"containerId": "date_0_2014_7_1",
"fromLabel": "From",
"currency": "PHP",
"price": 1929,
"formattedDate": "Fri, Aug 01, 2014", //data to get
"year": "2014",
"month": "7",
"day": "1",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
},
{
"startYear": 2014,
"startMonth": 7,
"startDay": 24,
"endYear": 2014,
"endMonth": 8,
"endDay": 23,
"selectedDate": "2014_8_8",
"departureStation": "Boracay (Caticlan)",
"arrivalStation": "Manila",
"departureStationCode": "(MPH)",
"arrivalStationCode": "(MNL)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_1_2014_7_24": {
"containerId": "date_1_2014_7_24",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Sun, Aug 24, 2014",
"year": "2014",
"month": "7",
"day": "24",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_1_2014_7_25": {
"containerId": "date_1_2014_7_25",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Mon, Aug 25, 2014",
"year": "2014",
"month": "7",
"day": "25",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
}
]
code:
var current = json[0].dateMarketHash;
var top = [];
var array = [];
for(var key in current){
top[0] = current[key].formattedDate;
top[1] = current[key].currency;
top[2] = current[key].price;
array.push(top);
}
document.write(array[0][0]); //prints "Fri, Aug 01, 2014" instead of "Thu, Jul 31, 2014"
document.write(array[1][0]); //prints "Fri, Aug 01, 2014"
It is because you initialize top outside the loop scope and that makes top[0] overwrite all references to the top array, which are being held in array
Put the top declaration inside the loop and see the difference
var current = json[0].dateMarketHash;
var array = [];
for(var key in current){
var top = [];
top[0] = current[key].formattedDate;
top[1] = current[key].currency;
top[2] = current[key].price;
array[array.length] = top;
}
http://jsfiddle.net/sUpC8/
If you insist on top being outside the loop scope you can work-around this problem by cloning the top array
var current = json[0].dateMarketHash;
var array = [];
var top = [];
for(var key in current){
top[0] = current[key].formattedDate;
top[1] = current[key].currency;
top[2] = current[key].price;
array[array.length] = top.slice(0);
}
Place "var top=[]" inside the loop and change array.push(top) to array.unshift(top), unshift method always insert element to the index 0.

Looping through unnamed array objects with backbone and dust

I have a JSON formed like you can see further below. I am having trouble looping through and defining the correct points to loop over, as I'm not that experienced with arrays in objects and complicated JSON.
What I'm mainly looking for is some pointers on the parse / toJSON parts of my collection, or other places I might be failing with this particular structure.
I am trying to loop over the values and output data from the event and the type name using backbone and dust. Normally I can just loop over my JSON by defining the collection in the view, e.g. calling this like so:
dust.render("dialog-decoderevents-items", { events : currentUser.eventList.toJSON() }, function(err, out) {
_this.$(".ab-tvg-prg-opt-future").append($(out));
});
That would normally allow me to just make a loop in dust and output data like this:
{#events}
{#tvProgram}{name}{/tvProgram}
{type}
{/events}
I have tried the dust examples using array and current context on this JSON and it will output something with no problem. I think the problem lies in what I define as the starting point of the model and collection.
I have both a parse function and a toJSON function in my collection now. But I also don't know what to define as an id on the model, since as you can see the id is defined inside the event, and not on the outside where I'd normally use it. Ideas? All the data is below.
JSON
{
"status": null,
"value": [
{
"event": {
"id": "RWtzdHJlbSBvcHBkcmFnZWxzZTxsZHR2cGQ+MTM2NDMwMDQwMDAwMDxsZHR2cGQ+MTM2NDMwNDAwMDAwMA==",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 13,
"minute": 20,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 14,
"minute": 20,
"seconds": 0
}
},
"type": "Party"
},
{
"event": {
"id": "Rmx5aW5nIFdpbGQgQWxhc2thPGxkdHZwZD4xMzY0MzA2NDAwMDAwPGxkdHZwZD4xMzY0MzEwMDAwMDAw",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 15,
"minute": 0,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 16,
"minute": 0,
"seconds": 0
}
},
"type": "Birthday"
},
{
"event": {
"id": "UG9pcm90PGxkdHZwZD4xMzY0MzE2NjAwMDAwPGxkdHZwZD4xMzY0MzE5NjAwMDAw",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 17,
"minute": 50,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 18,
"minute": 40,
"seconds": 0
}
},
"type": "Birthday"
},
{
"event": {
"id": "VGhlIEJpZyBCYW5nIFRoZW9yeTxsZHR2cGQ+MTM2NDMxOTAwMDAwMDxsZHR2cGQ+MTM2NDMyMDgwMDAwMA==",
"name": "A glorious event",
"description": "Some long description about the event",
"startTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 18,
"minute": 30,
"seconds": 0
},
"endTime": {
"year": 2013,
"month": 3,
"date": 26,
"hour": 19,
"minute": 0,
"seconds": 0
}
},
"type": "Birthday"
}]}
Model
var mainEvent = Backbone.Model.extend({
idAttribute : "id",
defaults : {
type: null,
event : {
id : null,
name: null,
description: null,
channelId: null,
startTime: null,
endTime: null
}
}
});
Collection
var eventCollection = Backbone.Collection.extend({
model: mainEvent,
parse : function(json, options) {
var retr = [], tmp;
if (json.status === ajaxStatus.success) {
switch(options.action) {
default:
retr = json.value;
break;
}
if (options.action === "events") {
currentUser.eventList = new eventCollection(retr, { action : "events" });
}
}
else if (json.status === ajaxStatus.notAuthenticated) {
currentUser.trigger("notLoggedIn");
return [];
}
return retr;
},
toJSON : function(){
var ret = this.constructor.__super__.toJSON.call(this);
// _.each(ret, function (item) {
// console.log('l1'+item);
// ret.push(item);
// });
return ret;
}
});
Idea after quickly reading over your issue (take it with a grain of salt as I've never used dust or backbone before):
Couldn't you just create a controller that stores a content array for each event object? That way, all you would have to do when you were extracting the JSON file is add each event to the controller, and iterate over that in your HTML. You could then extract the id with id = event[id] or something.
EDIT: Here's an example with AJAX, I know you're not using that but the parsing bit should at least be helpful:
function getParties() {
$.ajax({
url: 'json/party.json',
dataType: 'json',
async: false,
success: function(data) {
console.log("Data:", data.value);
for (var i=0, occurence; occurence = data.value[i]; i++) {
var event = {};
event.type = occurence.type;
for (var key in occurence.event) {
event[key] = occurence.event[key];
}
console.log("Event:", event);
// Do something with event... Maybe add to content array.
}
}
});
}
The "event" should now be in simple javascript. If you want to access a known field within it, you can say event["id"] for example. To iterate through all values, use the following loop.
for (var key in event) {
console.log("Key: " + key + ", Value: " + event[key]);
}
You also should be able to get the value with {id}, for example, in Backbone. Something similar works in Ember when the created "event" objects are pushed to some controller's content array, which is what I'm using.

Categories