May be you can help me with my task. I have a JSON string:
{
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
}
var my_id = 2692 /*My chats*/
/*Success JSON request below*/
onSuccess: function(m){
var messages = [];
var chanels = [];
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
}
chanels_u = chanels.unique(); /*We get id's: 62,66*/
}
My Question:
How can I create a new arrays dynamically (2 for this example for: 62 and 66) and push messages?
To 1 (62):
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"}
To 2 (66):
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
Thanks!
You are already identifying your chat ID and pushing it into the chanels array in your code:
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
chanels.push(m.chats[i].from_id);
}
You are also identifying unique IDs in your code:
chanels_u = chanels.unique();
All you need to do is locate your chats from the JSON object by comparing them to the IDs in chanels_u and if there's a match, push the text field to the messages array. This is should be close to what you require:
for(var i=0; i<m.chats.length;i++){
for(var j=0; j<chanels_u.length;j++){
if (my_id !== '' && m.chats[i].from_id === chanels_u[j]){
messages.push(m.chats[i].text);
}
}
}
this will do what you want, i believe - create a new object with keys of the to_id and from_id in a way that allows you to loop them whichever way you want. it would probably make more sense to have a toUser and fromUser objects that you can loop independently and cross reference as you build the replies but it's trivial to do so.
var chats = {
"chats":[
{"id":"1","time":"13:02", "from_id":"2692","text":"1","to_id":"62"},
{"id":"2","time":"13:48", "from_id":"62","text":"Hello!","to_id":"2692"},
{"id":"12","time":"15:47", "from_id":"2692","text":"3","to_id":"62"},
{"id":"13","time":"15:48", "from_id":"62","text":"4","to_id":"2692"},
{"id":"30","time":"08:57", "from_id":"2692","text":"To me","to_id":"62"},
{"id":"31","time":"09:28", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"66","text":"From user1","to_id":"2692"},
{"id":"32","time":"09:29", "from_id":"2692","text":"From user1","to_id":"66"}
],
"lastid": "32"
};
var newchats = {}, my_id = 2692;
chats.chats.each(function(chat) {
if (!chat.id || !chat.id.length || chat.from_id == my_id)
return;
newchats["from" + chat.from_id] = newchats["from" + chat.from_id] || [];
newchats["from" + chat.from_id].push(chat);
newchats["to" + chat.to_id] = newchats["to" + chat.to_id] || [];
newchats["to" + chat.to_id].push(chat);
});
console.log(newchats, JSON.encode(newchats));
see on jsfiddle http://jsfiddle.net/dimitar/7j2SN/, outputs:
{
"from62": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"}],
"to2692": [{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}],
"from66": [{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"}]
}
I guess, JSON is invalid. You missed to close the JSON properly.
{
"chats": [
{
"id": "1",
"time": "13:02",
"from_id": "2692",
"text": "1",
"to_id": "62"
},
{
"id": "2",
"time": "13:48",
"from_id": "62",
"text": "Hello!",
"to_id": "2692"
},
{
"id": "12",
"time": "15:47",
"from_id": "2692",
"text": "3",
"to_id": "62"
},
{
"id": "13",
"time": "15:48",
"from_id": "62",
"text": "4",
"to_id": "2692"
},
{
"id": "30",
"time": "08:57",
"from_id": "2692",
"text": "To me",
"to_id": "62"
},
{
"id": "31",
"time": "09:28",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
},
{
"id": "32",
"time": "09:29",
"from_id": "66",
"text": "From user1",
"to_id": "2692"
}
]
}
Use JSONLINT to validate your data. You can update(get/set) this array dynamically as you wish.
var msgBox={"chats":[]};
var msg={"id":1,"time":(new Date()).getTime(),"from_id":"","text":"","to_id":""};
var info={ // whole JSON data }
var chats=info['chats'];
for(m in chats){
console.log(chats[m].text) // will display the text
console.log(chats[m].time) // will display the time of chat
chat[m].to_id=32424; // you can modify the to_id value
}
You can make chanels and object instead of array.
onSuccess: function(m){
var messages = [];
var chanels = {};
var chanels_u = [];
for(var i=0; i<m.chats.length;i++){
if (my_id != '' && m.chats[i].from_id != parseInt(my_id)){
var fromID = m.chats[i].from_id;
if(!chanels[fromID]){
chanels[fromID] = [];
}
chanels[fromID].push(m.chats[i]);
}
}
//chanels_u = chanels.unique(); /*We get id's: 62,66*/
}
Related
How can I concatenate this json to obtain it:
complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"] ?
Each address can contain a set of complements which must be concatenated and separated by a comma.
P.s: I'm using javascript.
P.s2: Complements can be null like in the second group in JSON.
[
{
"postalcode": "1234",
"street": "ABC",
"number": "1",
"complement": [
{
"type": "B",
"name": "XYZ",
"description": "3"
},
{
"type": "C",
"name": "CDE",
"description": "TR"
},
{
"type": "D",
"name": "AAA",
"description": "5"
}
]
},
{
"postalcode": "444",
"street": "No complements",
"number": "5"
},
{
"postalcode": "2222",
"street": "BBB",
"number": "2",
"complement": [
{
"type": "E",
"name": "NDP",
"description": "3"
},
{
"type": "F",
"name": "DDD",
"description": "FR"
}
]
}
];
My code I'm getting this.complementsList.forEach is not a function.
getComplement(addressesResponse){
this.complementsList = JSON.parse(addressesResponse);
this.complementsList.forEach((item) => {
Object.defineProperty(item, 'complements', {
get: function() {
return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
})
});
Source: https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc
how i solved it :
arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');
Having a javascript object, you can go through the keys of the object and combine some of them into strings
It will look something like this:
const jsonObject = [{...}, {...}, ...]
const complements = [];
jsonObject.forEach((item) => {
let complement = item['complement'].reduce((result, currObj)
=> result += (currObj.name+' '+currObj.description), "");
complements.push(complement);
});
This is just an example. There are many ways to do it.
I'm trying to pick specific data from my JSON response which looks like this;
{
"status": "success",
"reservations": [
{
"id": "26630",
"subject": "Subject",
"modifiedDate": "2017-05-16T06:05:12",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T09:45:00",
"resources": [
{
"id": "2408",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3020",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "48",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildngName"
},
"name": "RoomName (PC)"
}
],
"description": ""
},
{
"id": "21173",
"subject": "subjectName",
"modifiedDate": "2017-05-16T06:05:20",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T16:00:00",
"resources": [
{
"id": "3115",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "2584",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "52",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildingName"
},
"name": "roomName (classroom)"
}
],
"description": ""
}
]
}
I've already used JSON.parse() to make it into an object and went through it with for-loops;
var json = JSON.parse(data.responseText);
for (var i = 0; i < json.reservations.length; i++) {
if (json.reservations[i].resources != null) {
for (var j = 0; j < json.reservations[i].resources.length; j++) {
var reservations = json.reservations[i];
var resources = json.reservations[i].resources[j];
}
}
}
So I would need to pick out the room names before the "description" key name:
"name": "roomName (PC)"
"name": "roomName (classroom)"
I've kept the JSON response a lot shorter for simplicity's sake but usually there's many more of these room names. The idea is to get all the room names from the JSON response body and push them to an array and just printing them out in order like this;
roomName (PC)
roomName (classroom)
Any quick and effective way to do this?
You can use such way:
const arrays = json.reservations
.filter(reservation => reservation.resources)
.map(reservation =>
reservation.resources.map(resource => resource.name)
)
;
const names = [].concat.apply([], arrays);
Array flatten taken from this question: Merge/flatten an array of arrays in JavaScript?
You can first iterate over the json.reservations array with Array.prototype.forEach() and then iterate again over r.resources and make a Array.prototype.push() if the expression: new RegExp(/roomName/, 'i').test(r.name) is satisfied.
Notice that in your json array have lowercase "name": "roomName (classroom)" and uppercase "name": "RoomName (PC)", so the Regular Expression will not check case sensitive with the flag i and finally the RegExp.prototype.test() will check if roomName is in the r.name.
Code:
var json = {"status": "success","reservations": [{"id": "26630","subject": "Subject","modifiedDate": "2017-05-16T06:05:12","startDate": "2017-05-16T08:00:00","endDate": "2017-05-16T09:45:00","resources": [{"id": "2408","type": "student_group","code": "groupCode","name": "groupName"},{"id": "3020","type": "realization","code": "realizationCode","name": "realizationName"},{"id": "48","type": "room","code": "roomCode","parent": {"id": "2","type": "building","code": "buildingCode","name": "buildngName"},"name": "RoomName (PC)"}],"description": ""},{"id": "21173","subject": "subjectName","modifiedDate": "2017-05-16T06:05:20","startDate": "2017-05-16T08:00:00","endDate": "2017-05-16T16:00:00","resources": [{"id": "3115","type": "realization","code": "realizationCode","name": "realizationName"},{"id": "2584","type": "student_group","code": "groupCode","name": "groupName"},{"id": "52","type": "room","code": "roomCode","parent": {"id": "2","type": "building","code": "buildingCode","name": "buildingName"},"name": "roomName (classroom)"}],"description": ""}]},
result = [],
regex = new RegExp(/roomName/, 'i');
json.reservations.forEach(function (r) {
r.resources.forEach(function (r) {
regex.test(r.name) && result.push({
name: r.name
});
});
})
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can simply do this:
var a = {
"status": "success",
"reservations": [
{
"id": "26630",
"subject": "Subject",
"modifiedDate": "2017-05-16T06:05:12",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T09:45:00",
"resources": [
{
"id": "2408",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3020",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "48",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildngName"
},
"name": "RoomName (PC)"
}
],
"description": ""
},
{
"id": "21173",
"subject": "subjectName",
"modifiedDate": "2017-05-16T06:05:20",
"startDate": "2017-05-16T08:00:00",
"endDate": "2017-05-16T16:00:00",
"resources": [
{
"id": "3115",
"type": "realization",
"code": "realizationCode",
"name": "realizationName"
},
{
"id": "2584",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "52",
"type": "room",
"code": "roomCode",
"parent": {
"id": "2",
"type": "building",
"code": "buildingCode",
"name": "buildingName"
},
"name": "roomName (classroom)"
}
],
"description": ""
}
]
}
var b = [];
a.reservations.forEach(function(item){
item.resources.forEach(function(obj){
if(obj.type == "room"){
b.push(obj.name)
}
})
});
console.log(b); //outputs desired array
var jsonStr = "{ \"status\": \"success\", \"reservations\": [ { \"id\": \"26630\", \"subject\": \"Subject\", \"modifiedDate\": \"2017-05-16T06:05:12\", \"startDate\": \"2017-05-16T08:00:00\", \"endDate\": \"2017-05-16T09:45:00\", \"resources\": [ { \"id\": \"2408\", \"type\": \"student_group\", \"code\": \"groupCode\", \"name\": \"groupName\" }, { \"id\": \"3020\", \"type\": \"realization\", \"code\": \"realizationCode\", \"name\": \"realizationName\" }, { \"id\": \"48\", \"type\": \"room\", \"code\": \"roomCode\", \"parent\": { \"id\": \"2\", \"type\": \"building\", \"code\": \"buildingCode\", \"name\": \"buildngName\" }, \"name\": \"RoomName (PC)\" } ], \"description\": \"\" }, { \"id\": \"21173\", \"subject\": \"subjectName\", \"modifiedDate\": \"2017-05-16T06:05:20\", \"startDate\": \"2017-05-16T08:00:00\", \"endDate\": \"2017-05-16T16:00:00\", \"resources\": [ { \"id\": \"3115\", \"type\": \"realization\", \"code\": \"realizationCode\", \"name\": \"realizationName\" }, { \"id\": \"2584\", \"type\": \"student_group\", \"code\": \"groupCode\", \"name\": \"groupName\" }, { \"id\": \"52\", \"type\": \"room\", \"code\": \"roomCode\", \"parent\": { \"id\": \"2\", \"type\": \"building\", \"code\": \"buildingCode\", \"name\": \"buildingName\" }, \"name\": \"roomName (classroom)\" } ], \"description\": \"\" } ] }";
var json = JSON.parse(jsonStr);
var array = [];
for (var i = 0; i < json.reservations.length; i++) {
if (json.reservations[i].resources != null) {
for (var j = 0; j < json.reservations[i].resources.length; j++) {
var resource = json.reservations[i].resources[j];
if (resource.type === "room") {
if (array.indexOf("code")) {
array.push(resource.name);
}
}
}
}
}
console.log(array);
output in console. Please check..
(2) ["RoomName (PC)", "roomName (classroom)"]0: "RoomName (PC)"1: "roomName (classroom)"length: 2__proto__: Array(0)
I'm trying to pick some data from my JSON response text which looks like this:
{
"status": "success",
"reservations": [
{
"id": "22959",
"subject": "SubjectName",
"modifiedDate": "2017-04-03T06:04:24",
"startDate": "2017-04-03T12:15:00",
"endDate": "2017-04-03T17:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "buildingName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "3137",
"type": "realization",
"code": "codeName",
"name": ""
},
{
"id": "3211",
"type": "realization",
"code": "codeName",
"name": "name"
}
],
"description": ""
},
{
"id": "22960",
"subject": "subjectName",
"modifiedDate": "2017-04-04T06:04:33",
"startDate": "2017-04-04T10:00:00",
"endDate": "2017-04-04T16:00:00",
"resources": [
{
"id": "17",
"type": "room",
"code": "codeName",
"parent": {
"id": "2",
"type": "building",
"code": "codeName",
"name": ""
},
"name": ""
},
{
"id": "2658",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
},
{
"id": "2446",
"type": "student_group",
"code": "groupCode",
"name": "groupName"
}
],
"description": ""
}
]
}
I've been trying to use JSON.parse() and go through the response text with a for-loop with no success. I need to pick the subject names, room names, building names and both student_group names.
This is what my code currently looks like:
var getData = {
"startDate":,
"endDate":,
"studentGroup": [
""]
};
var data = new XMLHttpRequest();
data.onreadystatechange = function () {
if (data.readyState == 4 && data.status == 200) {
try {
// Parse JSON
var json = JSON.parse(data.responseText);
// for-loops
for (var i = 0; i < json.reservations.length; i++) {
for (var x = 0; x < json.reservations[i].length;
x++) {
document.getElementById("test").innerHTML =
json.reservations[i].subject;
}
}
} catch (err) {
console.log(err.message);
return;
}
}
};
// JSON query
data.open("POST", "URL", true, "APIKEY", "PASS");
data.setRequestHeader('Content-Type', 'application/json');
data.send(JSON.stringify(getData));
This only prints the last subject name if I have more than 1 of them.
How should I do this?
Once you have your data parsed, forget it once was JSON. Now you have a JavaScript object.
Check data.status to make sure everything went well.
Loop over data.reservations and, inside that, over data.reservations[i].resources.
You should treat your parsed data as an object, so to get you going, this will get all unique student group names from all returned resources:
var studentGroups = [];
for (var i = 0; i < json.reservations.length; i++) {
if(json.reservations[i].resources != null){
for(var j = 0; j < json.reservations[i].resources.length; j++){
var resource = json.reservations[i].resources[j];
if(resource.type === "student_group"){
if(studentGroups.indexOf("groupName"))
studentGroups.push(resource.name);
}
}
}
}
}
Of course I'm not sure in what format you want to get your result (should this be a flat array or maybe another JSON, maybe only first value is important for you?), but I think you should already have an idea how to handle the topic.
Aim: On click of a next/previous button the label changes to the next/previous category of that current slide. Category Slider Wireframe of what I want to achieve.
Background: I previously attempted this 'Obtain Next/Previous Value from Object'. However I had issues where I had to have this in my ng-repeat and even though the data I wanted was produced it did not function with the bxSlider plugin (I could not duplicate the arrows). Therefore I need to maintain these arrows and labels outside of my ng-repeat.
Next Solution: I realised potentially the best solution for this would be to keep this outside the ng-repeat. In order to do so I believe I would have to variable attached to the scope that will increment/decrement. So the appropriate Next/Previous buttons can be viewed.
I naively attempted ng-click="activeCat = activeCat + 1" however that obviously just added ones to the end of the category.
Any help is greatly appreciated :)
HTML
<!-- Next & Previous Buttons -->
<div class="btn-nextprev">
<div class="next-container">
<a href="" class="btn btn-next" id="next" ng-click="nextCat = nextCat + 1">
{{ employees[getNextCategoryIndex($index)].category }} {{nextCat}}
</a>
</div>
<div class="prev-container">
<a href="" class="btn btn-prev" id="prev">
{{ employees[getPrevCategoryIndex($index)].category }} {{prevCat}}
</a>
</div>
</div>
<!-- END Next & Previous Buttons -->
Controller:
var personControllers = angular.module('personControllers', ['ngAnimate']);
//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http',
function($scope, $http) {
$http.get('../static/scripts/data2.json').
success(function(data) {
console.log("JSON file loaded");
console.log(data);
$scope.employees = data;
$scope.activeCat = data[0].category;
$scope.nextCat = data[0 + 1].category;
//$scope.prevCat = data[0 - 1].category;
}).
error(function(){
console.log("JSON file NOT loaded");
});
}]);
JSON:
[
{
"category": "Technology",
"shortname": "tech",
"icon": "fa-desktop",
"cat_id": 0,
"cards": [
{
"id": "card-1",
"name": "George Sofroniou",
"shortname": "G_Sof",
"age": "23",
"company": "Pirean Ltd.",
"role": "Graduate UI Developer"
},
{
"id": "card-2",
"name": "Steve Jobs",
"shortname": "S_Jobs",
"age": "56 (Died)",
"company": "Apple Inc.",
"role": "Former CEO"
},
]
},
{
"category": "Motors",
"shortname": "mot",
"icon": "fa-car",
"cat_id": 1,
"cards": [
{
"id": "card-1",
"name": "Elon Musk",
"shortname": "E_Musk",
"age": "43",
"company": "Tesla Motors",
"role": "CEO"
},
{
"id": "card-2",
"name": "Henry Ford",
"shortname": "H_Ford",
"age": "83 (Died)",
"company": "Ford Motor Company",
"role": "Founder"
}
]
},
{
"category": "Football",
"shortname": "foot",
"icon": "fa-futbol-o",
"cat_id": 2,
"cards": [
{
"id": "card-1",
"name": "Sir Alex Ferguson",
"shortname": "A_Fer",
"age": "73",
"company": "N/A",
"role": "Retired"
},
{
"id": "card-2",
"name": "Bobby Moore",
"shortname": "B_Moor",
"age": "51 (Died)",
"company": "N/A",
"role": "Footballer"
}
]
},
{
"category": "Law",
"shortname": "law",
"icon": "fa-gavel",
"cat_id": 3,
"cards": [
{
"id": "card-1",
"name": "Harvey Specter",
"shortname": "H_Spec",
"age": "43",
"company": "Pearson Specter Litt",
"role": "Name Partner"
},
{
"id": "card-2",
"name": "Saul Goodman (James Morgan McGill)",
"shortname": "S_Good",
"age": "48",
"company": "Better Call Saul",
"role": "Criminal Defence Attorney"
}
]
}
]
You could just store each objects data in an array, and have the array index increment or decrement depending on which button they press.
var i = 0
$scope.dataArray = [];
//sift the data into the array
$scope.next = function () {
i++
};
$scope.prev = function () {
i--
};
Here is an example:
http://plnkr.co/edit/SVXhxvwJqnO8Uarjkxx2?p=preview
GSof Edit:
//Next & Previous Button Category Label
$scope.i = 0;
$scope.j = $scope.employees.length;
$scope.nextCat = $scope.i + 1;
$scope.prevCat = $scope.j - 1;
$scope.getNext = function(){
//console.log($scope.nextCat);
$scope.nextCat++;
if( $scope.nextCat >= $scope.employees.length ){
$scope.nextCat = 0;
}
$scope.prevCat++;
if( $scope.prevCat >= $scope.employees.length ){
$scope.prevCat = 0;
}
};
$scope.getPrev = function(){
//console.log($scope.nextCat);
$scope.prevCat--;
if( $scope.prevCat < 0 ){
$scope.prevCat = $scope.employees.length - 1;
}
$scope.nextCat--;
if( $scope.nextCat < 0 ){
$scope.nextCat = $scope.employees.length - 1;
}
};
This if statement will insure that when the end of the array is reached the item will return to the beginning. The next and previous values are now in sync with each other so on press of the next button both the next and previous labels update and vice versa.
Again thank you for help.
On ng-click call function and in that function do the increment.
Like this
<a href="" class="btn btn-next" id="next" ng-click="increment()">
and in controllerjs
$scope.increment=function(){
$scope.flag=false;
angular.forEach($scope.employees,function(employe){
if(flag){
$scope.nextCat = employe.category;
return;
}
if($scope.nextCat === employe.category){
flag=true;
}
});
}
I am trying to use for..in loop to access the description key/value within 'Event' but at the moment am not fully sure how to achieve this. First of all I used the for..in and logged this out, this returns all the top level entries in the response, how do I now drill down and pick out Event.description? I first of all thought it was data[prop].Event.description but thats not the case. Should I be using a normal for loop and then the for..in inside of this?
Here is my current code:
$(document).ready(function() {
var data = {
"status": "ok",
"code": "200",
"message": "event details",
"data": [{
"Event": {
"id": "1",
"name": "Sample Event Number 1",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "1",
"name": "Support #1",
"BandsEvent": {
"id": "7",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "2",
"name": "Support #2",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}},
{
"Event": {
"id": "2",
"name": "Sample Event Number 2",
"description": "Sample Event Number 4 Description ....",
"event_date": "2012-05-31 00:00:00",
"Band": [{
"id": "2",
"name": "Another Crazy Band",
"BandsEvent": {
"id": "3",
"band_id": "2",
"event_id": "8",
"created": "2012-05-23 15:53:56",
"modified": "2012-05-23 15:53:56"
}},
{
"id": "4",
"name": "The Band",
"BandsEvent": {
"id": "8",
"band_id": "1",
"event_id": "8",
"created": "2012-05-23 15:53:57",
"modified": "2012-05-23 15:53:57"
}}]
}}]
}
var prop;
for (prop in data) {
console.log( data[prop] );
// data.Event.description
}
});
This should do what you want:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description);
}
I should add that the reason that your code doesn't work is that the "prop" variable would first be "status", then "code", then "message" and THEN "data". Status/code/message has no "Event" property, so therefore your code would return undefined if you'd try to access data[prop].Event. Here we pick them out specifically. And since that data.data is an array, there's no reason to use a for .. in loop, but rather just a regular for loop.
Likewise, if you would want to print out the descriptions AND the bands, you could do the following:
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].Event.description + " has the following bands:");
for (var j = 0; j < data.data[i].Event.Band.length; j++) {
console.log(data.data[i].Event.Band[j].name);
}
}