javascript arrays and JSON - javascript

I'm working on Bootstrap calendar and I've tried to make my array looks like this:
{
"success": 1,
"result": [
{
"id": "293",
"title": "This is warning class event with very long title to check how it fits to evet in day view",
"url": "http://www.example.com/",
"class": "event-warning",
"start": "1362938400000",
"end": "1363197686300"
},
{
"id": "256",
"title": "Event that ends on timeline",
"url": "http://www.example.com/",
"class": "event-warning",
"start": "1363155300000",
"end": "1363227600000"
},
{
"id": "276",
"title": "Short day event",
"url": "http://www.example.com/",
"class": "event-success",
"start": "1363245600000",
"end": "1363252200000"
},
{
"id": "294",
"title": "This is information class ",
"url": "http://www.example.com/",
"class": "event-info",
"start": "1363111200000",
"end": "1363284086400"
}
] }
But I've tried and got something like this:
[
{
"success":1
},
{
"result":[
{
"id":"1",
"title":"dev",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
},
{
"id":"2",
"title":"Holiday",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
},
{
"id":"3",
"title":"Coding...",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
},
{
"id":"4",
"title":"data",
"url":"www.example.com",
"class":"event-success",
"start":"0",
"end":"0"
}
]
}
]
and my code to create those mess are
var result = [];
for(i=0; i<rows.length; i++) {
var result_single = {id:rows[i].uid, title:rows[i].name, url:"www.example.com", class:"event-success", start:rows[i].startdate, end:rows[i].enddate};
result.push(result_single);
}
var output = new Array();
output.push(data);
result = {result:result};
output.push(result);
console.log(JSON.stringify(output));
To be honest, I don't quite understand how array in js works. can somebody point out how did i go wrong?

Your expected result is an object which contains 2 properties, but you get an array which contains two objects. I think you want the first result which is object with two properties.
var result = [];
var rows = [1,2,3,4,5];
for(i=0; i<rows.length; i++) {
var result_single = {id:rows[i], title:rows[i], url:"www.example.com", class:"event-success", start:rows[i].startdate, end:rows[i].enddate};
result.push(result_single);
}
var output = {
success: 1,
result: result
}
console.log(JSON.stringify(output));

Related

Compare Arrays and Remove Duplicates from the Final Array. Pokedex App

I create a Pokédex app, but i ran in some Problems with the double type Pokémon:
I call pokeapi twice to 2 endpoints (one for each Type), and i need to compare the Results in different Ways.
let a = {
"double_damage_from": [
{
"name": "ground",
"url": "https://pokeapi.co/api/v2/type/5/"
},
{
"name": "rock",
"url": "https://pokeapi.co/api/v2/type/6/"
},
{
"name": "water",
"url": "https://pokeapi.co/api/v2/type/11/"
}
],
"half_damage_from": [
{
"name": "bug",
"url": "https://pokeapi.co/api/v2/type/7/"
},
{
"name": "steel",
"url": "https://pokeapi.co/api/v2/type/9/"
},
{
"name": "fire",
"url": "https://pokeapi.co/api/v2/type/10/"
},
{
"name": "grass",
"url": "https://pokeapi.co/api/v2/type/12/"
},
{
"name": "ice",
"url": "https://pokeapi.co/api/v2/type/15/"
},
{
"name": "fairy",
"url": "https://pokeapi.co/api/v2/type/18/"
}
],
"no_damage_from": []
};
let b = {
"double_damage_from": [
{
"name": "fighting",
"url": "https://pokeapi.co/api/v2/type/2/"
},
{
"name": "ground",
"url": "https://pokeapi.co/api/v2/type/5/"
},
{
"name": "steel",
"url": "https://pokeapi.co/api/v2/type/9/"
},
{
"name": "water",
"url": "https://pokeapi.co/api/v2/type/11/"
},
{
"name": "grass",
"url": "https://pokeapi.co/api/v2/type/12/"
}
],
"half_damage_from": [
{
"name": "normal",
"url": "https://pokeapi.co/api/v2/type/1/"
},
{
"name": "flying",
"url": "https://pokeapi.co/api/v2/type/3/"
},
{
"name": "poison",
"url": "https://pokeapi.co/api/v2/type/4/"
},
{
"name": "fire",
"url": "https://pokeapi.co/api/v2/type/10/"
}
],
"no_damage_from": []
};
I need to Compare the Data and get the Matches in a array.
This works fine and i got the 4x, 1x, and 1/4x damage in a array:
getMatch(a, b) {
let matches = [];
for (let i = 0; i < a.length; i++) {
for (let e = 0; e < b.length; e++) {
if (a[i].name === b[e].name) matches.push(a[i]);
}
}
return matches;
}
compareTypes(a, b) {
let four_damage_from = this.getMatch(a.double_damage_from, b.double_damage_from);
let double_damage_from = [];
let normal_damage_from = this.getMatch(a.double_damage_from, b.half_damage_from);
let half_damage_from = [];
let quarter_damage_from = this.getMatch(a.half_damage_from, b.half_damage_from);
let no_damage_from = this.getMatch(a.no_damage_from, b.no_damage_from);
let matches = { four_damage_from, double_damage_from, normal_damage_from, half_damage_from, quarter_damage_from, no_damage_from };
return matches;
}
to find the correct types for double_damage_from i have to merge a.double_damage_from and b.double_damage_from e.g. to c.double_damage_from. then i have to remove from c.double_damage_from all types that are in four_damage_from, normal_damage_from, quarter_damage_from, no_damage_from to get the correct 2x types, the same with half_damage_from.
I tried many solution but i didn't figure out how to solve this.
greetings Raphi
It Works with lodash, i need to think a bit about but basically works.
removeMatch(union, remove, double = false) {
union = _.differenceBy(union, remove.four_damage_from, 'name');
union = _.differenceBy(union, remove.normal_damage_from, 'name');
union = _.differenceBy(union, remove.quarter_damage_from, 'name');
// union = _.differenceBy(union, remove.no_damage_from, 'name');
if(double) {
union = _.differenceBy(union, remove.half_damage_from, 'name');
} else {
union = _.differenceBy(union, remove.double_damage_from, 'name');
}
return union;
}

Compare two json files and add number to object if object with same value is still there

Lets say i have 2 Json responses from a server, one of which is 30 seconds older that the new one. How would i be able to check if an object is still inside the response and after testing if it is still there update an object in another json file to add +1 to the number of that object.
(an example because i can´t explain)
JSON coming in
"names and id´s in json changed"
{
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [
{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
}
After cutting out wanted values it looks like this :
[
'07bda75d-d8d2-4108-94a7-ba2c09127nsj',
'8d8aac43-112b-402b-8771-67b49183lazf',
'67d8a66b-ce37-439f-9020-e6de827dn2o9'
]
What i want to do
Now upon a new response coming in i want to update another json file which should idealy look something like this...
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
...and add 1 to the number behind a the certain playerid.
Something like this should work.
let samplePayload = {
"description": "Insert description here;",
"favicon": null,
"latency": 78.085,
"players": {
"max": 20,
"online": 3,
"sample": [{
"id": "07bda75d-d8d2-4108-94a7-ba2c09127nsj",
"name": "oajhebskaa"
},
{
"id": "8d8aac43-112b-402b-8771-67b49183lazf",
"name": "jahebianl"
},
{
"id": "67d8a66b-ce37-439f-9020-e6de827dn2o9",
"name": "ffwqehas"
}
]
},
"version": {
"name": "Paper 1.16.4",
"protocol": 754
}
};
let previousResponseIds = [];
let trackingObj = {};
function responseMiddleware(payload) {
let responseIds = payload.players.sample.map(v => v.id);
let matches = previousResponseIds.filter(v => responseIds.find(x => x === v));
for (let i = 0; i < matches.length; i++) {
if (trackingObj.hasOwnProperty(matches[i])) trackingObj[matches[i]] += 1;
else trackingObj[matches[i]] = 0;
}
previousResponseIds = responseIds;
}
/*UI below*/
let pre = document.getElementsByTagName('pre')[0];
(function updateUI() {
pre.innerText = JSON.stringify(trackingObj, null, 1);
setTimeout(updateUI, 200);
})();
document.getElementById("AddResponse").addEventListener("click", function() {
responseMiddleware(samplePayload);
});
<strong>trackingObj:</strong>
<pre></pre>
<button id="AddResponse">Simulate Response</button>
Let's start with
{
"players" : [
{ "07bda75d-d8d2-4108-94a7-ba2c09127nsj": "0" },
{ "8d8aac43-112b-402b-8771-67b49183lazf": "0" },
{ "67d8a66b-ce37-439f-9020-e6de827dn2o9": "0" }
]
}
let mainObj = JSON.parse(response1);
let players = JSON.parse(response2);
for (let entry of mainObj.players.sample) {
if (players.players.indexOf(entry.id) > -1) {
players.players[entry.id]++;
}
}
I don't have a chance to test it right this moment, give it a shot, and it should put you on the right track.

JSON array length

Here is my JSON array code
var App = [
{
"id": "123",
"caption": "Test",
"description": "Test Desc"
},
{
"id": "345",
"caption": "adsasdasd",
"description": ""
},
{
"id": "456",
"caption": "adsasdasd",
"description": ""
},
{
"id": "578",
"caption": "adsasdasd",
"description": ""
}
]
i tried with the following code
var obj = $.parseJSON(App);
alert(JSON.stringify(obj,4,null));
var AppLen = obj[i].length;
alert(AppLen);
but i didn't get any solution. Let me know if i missed any thing to get the JSON object array length.
your data is already json format:do like this
var App = [
{
"id": "123",
"caption": "Test",
"description": "Test Desc"
},
{
"id": "345",
"caption": "adsasdasd",
"description": ""
},
{
"id": "456",
"caption": "adsasdasd",
"description": ""
},
{
"id": "578",
"caption": "adsasdasd",
"description": ""
}
];
console.log(App);
console.log(App[0].length);// you can not get length from this because it is not array it's an object now.
var AppLen = App.length;
alert(AppLen);
obj.size() or obj.length
If that dont run try this: Length of a JavaScript object
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
// Get the size of an object
var size = Object.size(myArray);

Backbone - Parse object into models for collection

I am getting an object with several nested objects back from a collection.fetch() call. Is there a way to parse these sub-objects and pass them into the collection as individual models?
Here is an example of the data I am getting back. I'd like to pass this into the collection as 3 models when it is fetched from the server.
Here is a fiddle to what I am trying but I am not sure of the best way to go about this: http://jsfiddle.net/L8ov7oo5/
Data from server:
{
"slides": {
"date": "August 21, 2014",
"Author": "Luke Skywalker",
"slide1": {
"content": {
"headline": "headline 1",
"desc": "description for slide 1",
"image": [
{
"url": "http://placekitten.com/100/100",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
},
"slide2": {
"content": {
"headline": "headline2",
"desc": "descriptionforslide2",
"image": [
{
"url": "http: //placekitten.com/125/125",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
},
"slide3": {
"content": {
"headline": "headline3",
"desc": "descriptionforslide3",
"image": [
{
"url": "http: //placekitten.com/150/150",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
}
}
}
Example of model I'd like to pass to the collection:
{
"slide1": {
"content": {
"headline": "headline 1",
"desc": "description for slide 1",
"image": [
{
"url": "http://placekitten.com/100/100",
"type": "thumbnail",
"alt": "imageofakitten"
}
]
}
}
}
Here is my code, but when I log the results of the collection.fetch() I don't see 3 models in the collection.
var MyModel = Backbone.Model.extend({});
var MyCollection = Backbone.Collection.extend({
model: MyModel,
url: 'https://api.mongolab.com/api/1/databases/parse-test/collections/parse-test-collection?apiKey=x5akja343lqkja',
parse: function (response) {
console.log('response', response);
for (var prop in response[0].slides) {
if ( response[0].slides.hasOwnProperty(prop) ) {
// Try to add an object as a 'model' to the 'collection'
this.add( response[0].slides[prop] );
}
}
return response;
}
});
var myCollection = new MyCollection();
myCollection.fetch().done(function () {
// Expecting to see 3 models in this collection but I am not.
console.log(myCollection);
});
simply you can remove the properties date and Author and return the slides
parse: function (response) {
//console.log('response', response[0]['slides']);
delete response[0]['slides'].date;
delete response[0]['slides'].Author;
var temp = [];
$.each( response[0]['slides'], function(index, val) {
temp.push(val);
});
return temp;
}
DEMO
The parse call for your collection should return an array. Inside your for-in loop, add each of the objects you want to an array and return the array from parse when you're done.
var obj = response[0].slides,
returnList = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop) && prop !== 'date' && prop !== 'Author') {
returnList.push(obj[prop]);
}
}
return returnList;
here's a jsfiddle to demonstrate.
EDIT: here's another jsfiddle to demonstrate using _.map() instead of a for-in loop.
var obj = response[0].slides;
delete obj.date;
delete obj.Author;
return _.map(obj, function (value, key) {
return obj[key];
});

Javascript/jQuery Check duplicate Values in Objects

I have an array of objects, which has an array of 'tracks.' What I would like to do is compare the mbid values across all of the track objects, check if there are any duplicates, and store the duplicate track objects into a new array. Any help or guidance?
[
{
"track": [
{
"name": "Radiapathy",
"mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
"url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
},
{
"name": "How Did I Get Here",
"mbid": "64b3078f-89cd-4ad5-bc7a-b43af082b00f",
"url": "http://www.last.fm/music/Odesza/_/How+Did+I+Get+Here"
},
{
"name": "Sunshine Roof",
"mbid": "837db975-c93e-45ca-992c-0c924ef0f34f",
"url": "http://www.last.fm/music/The+Innocence+Mission/_/Sunshine+Roof"
}
]
},
{
"track": [
{
"name": "Traveling",
"mbid": "b40c24b8-3295-4219-af59-855b69958ca2",
"url": "http://www.last.fm/music/Tennis/_/Traveling"
},
{
"name": "Ghost",
"mbid": "6273ae8f-3d2c-44c6-8c0d-53013ba79b4e",
"url": "http://www.last.fm/music/Neutral+Milk+Hotel/_/Ghost"
},
{
"name": "Strange",
"mbid": "5a015df2-6c4a-4192-bea8-14ec5f297713",
"url": "http://www.last.fm/music/Built+to+Spill/_/Strange"
}
]
},
{
"track": [
{
"name": "Radiapathy",
"mbid": "4c0767f1-1c2e-4790-a8d1-ee7f78f0ac84",
"url": "http://www.last.fm/music/The+Velvet+Teen/_/Radiapathy"
},
{
"name": "Let Me Show You Love",
"mbid": "",
"url": "http://www.last.fm/music/Cut+Copy/_/Let+Me+Show+You+Love"
},
{
"name": "Footsteps",
"mbid": "",
"url": "http://www.last.fm/music/Cut+Copy/_/Footsteps"
}
]
}
]
The answer to this question (Elminating duplicates in a JSON object) pretty much answers yours. I've used this (the "Smart(er) way") and modified to suit your array & requirements:
var key = null;
var noDupes = [];
var dupes = [];
for (var i = 0; i < arr.length; i++)
{
// loop through each track:
for (var j = 0; j < arr[i].track.length; j++)
{
key = arr[i].track[j].mbid;
if (!hash.contains(key))
{
hash.add(key);
noDupes.push(arr[i].track[j]); // if not duplicate
}
else
{
dupes.push(arr[i].track[j]); // if duplicate
}
}
}
http://jsfiddle.net/6wspy/

Categories