Reputation: 113
I can keep adding or removing records from my array and it will work fine until it gets to the last one, even if the record is an exact copy of one it has already worked on.
Array:
[
{
"adID": "1",
"isDefault": "false",
"adName": "Ad 1 Name",
"adDesc": "Ad 1 Description",
"adURL": "",
"adFormat": "image",
"adImages": {
"adImageDSK": "../img/bgfour.jpg",
"adImageDEV": "../img/bgfour.jpg"
}
},
{
"adID": "2",
"isDefault": "true",
"adName": "Ad 2 Name",
"adDesc": "Ad 2 Description",
"adURL": "",
"adFormat": "image",
"adImages": {
"adImageDSK": "../img/bgnine.jpg",
"adImageDEV": "../img/bgnine.jpg"
}
},
{
"adID": "3",
"isDefault": "false",
"adName": "Ad 3 Name",
"adDesc": "Ad 3 Description",
"adURL": "",
"adFormat": "image",
"adImages": {
"adImageDSK": "../img/bgseven.jpg",
"adImageDEV": "../img/bgseven.jpg"
}
},
{
"adID": "4",
"isDefault": "false",
"adName": "Ad 4 Name",
"adDesc": "Ad 4 Description",
"adURL": "",
"adFormat": "image",
"adImages": {
"adImageDSK": "../img/bgfive.jpg",
"adImageDEV": "../img/bgfive.jpg"
}
}
]
jQuery:
$.getJSON("../json/adverts.json", function (data) {
"use strict";
function loadAdData() {
adArray = [];
$.map(data, function (item) {
adArray.push({
'isDefault': item.isDefault,
'adID': item.adID,
'adName': item.adName,
'adDesc': item.adDesc,
'adURL': item.adURL,
'adFormat': item.adFormat,
'adImageDSK': item.adImages.adImageDSK,
'adImageDEV': item.adImages.adImageDEV
});
});
}
loadAdData();
var defArray = adArray;
console.log(defArray);
var newArray = [];
$.each(defArray, function (i, item) {
if (item.isDefault === 'true') {
newArray.push({
'adID': item.adID,
'adName': item.adName,
'adDesc': item.adDesc,
'adURL': item.adURL,
'adFormat': item.adFormat,
'adImageDSK': item.adImageDSK,
'adImageDEV': item.adImageDEV
});
defArray.splice($.inArray([i], defArray), 1);
} else {
console.log(item.adID);
}
})
}
The real array is 10 items long, but they are copy and pastes of the above with the numbers changed. I'm pulling some adverts from a file and checking to see if any of them are 'defaults' that have to show, put them in a different array for use later on.
Upvotes: 2
Views: 219
Reputation: 338406
I think you simply want to filter the array.
function Advert(data) {
this.isDefault = data.isDefault;
this.adID = data.adID;
this.adName = data.adName;
this.adDesc = data.adDesc;
this.adURL = data.adURL;
this.adFormat = data.adFormat;
this.adImageDSK = data.adImages ? data.adImages.adImageDSK : null;
this.adImageDEV = data.adImages ? data.adImages.adImageDEV : null;
}
$.getJSON("../json/adverts.json").done(function (data) {
var allAds = data.map(function (item) {
return new Advert(item);
});
var defaultAds = allAds.filter(function (ad) {
return ad.isDefault === 'true';
});
// ...
});
Upvotes: 1