How to iterate through an object with key and get the value - javascript

So I am not sure why I having such a difficult time with this, but I have an object I am trying to map over to get a value from it.
For example:
let obj = {
"lyzjmpkvbtocygakcoxu": {
"label": "Show Time",
"hour": "12",
"minute": "00",
"period": "p.m.",
"add_time": "enabled",
"bdlmynfythqgyzrhruhw_add_date": "December 01, 2021",
"bdlmynfythqgyzrhruhw_stock": ""
},
"eueuuzvkteliefbnwlii": {
"label": "Show Time",
"hour": "05",
"minute": "00",
"period": "p.m.",
"add_time": "enabled",
"brtmypzvuooqhvqugjbj_add_date": "December 02, 2021",
"brtmypzvuooqhvqugjbj_stock": ""
}
}
I want to be able to get this:
December 01, 2021, December 02, 2021
I was able to do this to get the values and key for "add_time", however what I want is values for key containing the "..._add_date".
Object.keys(obj).reduce(
(acc, elem) => {
acc[elem] = obj[elem].add_time;
return acc;
},
{},
);

I suppose you could search through the keys and .find the one that matches the pattern...
let obj = {
"lyzjmpkvbtocygakcoxu": {
"label": "Show Time",
"hour": "12",
"minute": "00",
"period": "p.m.",
"add_time": "enabled",
"bdlmynfythqgyzrhruhw_add_date": "December 01, 2021",
"bdlmynfythqgyzrhruhw_stock": ""
},
"eueuuzvkteliefbnwlii": {
"label": "Show Time",
"hour": "05",
"minute": "00",
"period": "p.m.",
"add_time": "enabled",
"brtmypzvuooqhvqugjbj_add_date": "December 02, 2021",
"brtmypzvuooqhvqugjbj_stock": ""
}
}
const result = Object.values(obj)
.map(val =>
Object.entries(val)
.find(([key]) => key.endsWith('_add_date'))
[1]
)
.join(', ');
console.log(result);
But a much better approach would be to fix the upstream code so it doesn't create such a strange structure to begin with.

Related

reduce & sum array of objects entries

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);

What's the best way to group a JSON object by a certain value?

I want to be able to display data in an React application like so:
Today
- Batman entered the watchtower at 10:30am
- Batman entered the watchtower at 10:15am
- Wonder Woman entered the watchtower at 10:00am
Yesterday
- Flash entered the watchtower at 10:30am
- Green Lantern entered the watchtower at 10:15am
- Cyborg entered the watchtower at 10:00am
9th August 2018
- Aquaman entered the watchtower at 10:30am
The data being sent to me is an JSON Array of objects:
[{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400" // Epoch timestamp equating to 11th August 2018 at 10:30am
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500" // Epoch timestamp equating to 11th August 2018 at 10:15am
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600" // Epoch timestamp equating to 11th August 2018 at 10:00am
},
{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000" // Epoch timestamp equating to 10th August 2018 at 10:30am
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100" // Epoch timestamp equating to 10th August 2018 at 10:15am
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800" // Epoch timestamp equating to 10th August 2018 at 10:00am
},
{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600" // Epoch timestamp equating to 9th August 2018 at 10:30am
}]
I am not sure what's the best way to use this JSON Array to render the data in the way that I need. I thought I may need to process the data further in a new object like below but am not sure the best way to do so.
[{
"11-August-2018" : [{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400" // 11th August 2018 at 10:30am
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500" // 11th August 2018 at 10:15am
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600" // 11th August 2018 at 10:00am
}],
"10-August-2018" : [{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000" // 10th August 2018 at 10:30am
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100" // 10th August 2018 at 10:15am
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800" // 10th August 2018 at 10:00am
}],
"09-August-2018" : [{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600" // 9th August 2018 at 10:30am
}]
}]
Sorting, mapping, reducing. Gotta love es2018
(d => {
// a few utility methods
const dateFromEpoch = epochStr => new Date(new Date(0).setUTCSeconds(+epochStr));
const padLeft = n => `${n}`.padStart(2, "0");
const removeTime = dateTime => new Date(dateTime.toISOString().split("T")[0]);
const getDateLabel = dateTime => {
const now = removeTime(new Date());
const plainDate = removeTime(dateTime);
const dayDiff = Math.abs(Math.round(((plainDate - now) / 3600000) / 24));
return dayDiff < 1 ?
"Today" :
dayDiff === 1 ?
"Yesterday" :
`${dayDiff} Days ago`;
};
const heroicData = getHeroicData()
.sort((a, b) => +a.timestamp < +b.timestamp) // sort descending
.reduce(heroicReducer, {}); // create reshuffled object
// the heroic entry points
d.querySelector("#raw").textContent = JSON.stringify(heroicData, null, " ");
// create html output using a reducer
d.querySelector("#result").innerHTML = Object.keys(heroicData)
.reduce((reduced, day) =>
reduced.concat(`
<b>${day}</b>
<ul>
${heroicData[day].map(visit => `<li>${visit}</li>`).join("")}
</ul>`), [])
.join("");
function heroicReducer(reduced, heroicVisit) {
const dateTime = dateFromEpoch(heroicVisit.timestamp);
const reportKey = getDateLabel(dateTime);
const reportString = `<heroe>${
heroicVisit.name}</heroe> entered the watchtower at ${
padLeft(dateTime.getHours())}:${
padLeft(dateTime.getMinutes())}`;
if (reduced[reportKey]) {
reduced[reportKey].push(reportString)
} else {
reduced[reportKey] = [reportString];
}
return reduced;
}
function getHeroicData() {
return [{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400"
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500"
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600"
},
{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000"
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100"
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800"
},
{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600"
}
];
}
})(document);
body {
font: normal 12px/15px verdana, arial;
margin: 3em;
}
heroe {
color: red;
font-style: italic;
}
<pre id="raw"></pre>
<h3>**Reduced to output</h3>
<div id="result"></div>
You can group data with reduce function for example, also you can format date object by yourself or if you need some complex formatting in future you can use moment.js library(render "today", "yesterday", "th", "rd" etc). So I don't map month names and used just UTC in my example:
let data = [{
"name": "Batman",
"secret_identity": "Bruce Wayne",
"timestamp": "1533983400" // Epoch timestamp equating to 11th August 2018 at 10:30am
},
{
"name": "Superman",
"secret_identity": "Clark Kent",
"timestamp": "1533982500" // Epoch timestamp equating to 11th August 2018 at 10:15am
},
{
"name": "Wonder Woman",
"secret_identity": "Diana Prince",
"timestamp": "1533981600" // Epoch timestamp equating to 11th August 2018 at 10:00am
},
{
"name": "Flash",
"secret_identity": "Wally West",
"timestamp": "1533897000" // Epoch timestamp equating to 10th August 2018 at 10:30am
},
{
"name": "Green Lantern",
"secret_identity": "Hal Jordan",
"timestamp": "1533896100" // Epoch timestamp equating to 10th August 2018 at 10:15am
},
{
"name": "Cyborg",
"secret_identity": "Victor Stone",
"timestamp": "1533895800" // Epoch timestamp equating to 10th August 2018 at 10:00am
},
{
"name": "Aquaman",
"secret_identity": "Arthur Curry",
"timestamp": "1533810600" // Epoch timestamp equating to 9th August 2018 at 10:30am
}]
let result = data.reduce((acc, item) => {
let date = new Date(item.timestamp*1000);
let key = `${date.getUTCDate()}-${date.getUTCMonth()+1}-${date.getUTCFullYear()}`;
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, {})
console.log(result)
There are two smaller problems that you are trying to solve here:
Mapping epoch to date,
Grouping events by date
I'll use utility libraryramda to simplify the answer, but you could implement your own groupBy function if you wanted to.
Possible solution:
const epochToDate = epoch => {
const date = new Date(epoch)
return `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`
}
const groupedJson = R.groupBy(
event => epochToDate(parseInt(event.timestamp, 10)),
rawJson
)
You can play with it in ramda repl.
u have to import the json file to your react application like this
import data from './data.json'
this.data = data
and just work with it like any other object
outJSON= [ {team: "TeamA",name: "Ahmed",field3:"val3"}, {team: "TeamB",name: "Ahmed",field3:"val43"}, {team: "TeamA",name: "Ahmed",field3:"val55"} ]
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var groubedByTeam=groupBy(outJSON, 'team')
console.log(groubedByTeam);

array formatiing in javascript

I have an json array like this
var data= [
{
"id": 24,
"title": "BCOM",
"start": "2014-08-05 12:59:00 PM",
"end": "2014-08-05 2:59:00 PM",
"description": "mcom",
"DIFF": 120
},
{
"id": 26,
"title": "MCOM",
"start": "2014-08-10 12:59:00 PM",
"end": "2014-08-10 4:59:00 PM",
"description": "mcom",
"DIFF": 240
},
{
"id": 29,
"title": "MCOM",
"start": "2014-08-11 12:59:00 PM",
"end": "2014-08-11 8:59:00 PM",
"description": "mcom",
"DIFF": 480
},
{
"id": 30,
"title": "MCOM",
"start": "2014-08-13 12:59:00 PM",
"end": "2014-08-13 4:59:00 PM",
"description": "mcom",
"DIFF": 240
}
]
I want to make this array having index with out double quotes and change some index names , and some other modifications by using javascript array functions.
like
var data = [
{
id: 24,
title:"MCOM",
y: 120
},
{
id: 26,
title:"MCOM",
y: 240,
},
{
id: 29,
title:"MCOM",
y: 480,
},
]
Please help me in this, Thank you
Indexes with quotes ({ "title": "asdf" }) are equivalent to indexes without quotes ({ title: "asdf" }) in javascript, except that you can use more symbols like spaces, brackets or keywords in the quoted version.
Also, in JSON, you HAVE to add quotes around indexes, otherwise it's not valid JSON.
About the modifications, you can use Array.prototype.map() to do this
var newData = data.map(function (el) {
return {
id: el.id,
title: el.title,
y: el.DIFF
};
});
console.log(newData);
Use Array map function for this
var result = data.map(function (obj) {
return {id:obj.id,title:obj.title,y:obj.DIFF};
})
console.log(result);
I'm assuming in the result there should be BCOM as title for id, 24. I this is a type that there it's written as MCOM.
what I think "" shouldn't matter for keys.
Do some googling ;-) it will help..
var data = '{ "name": "John Smith" }'; //Let's say you got this
data = data.replace(/\"([^(\")"]+)\":/g,"$1:"); //This will remove all the quotes
data; //'{ name: "John Smith" }'
Hope it helps.

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