New to AngularJS so apologies if my terminology isn't correct. I am trying to call a value that is in my JSON body, however the difference is that it's also inside another body called student.
{
"id": 3,
"teacherName": "N/A",
"students": [
{
"student": "n/a"
}
],
"status": "ALIVE"
}
My JS code consists of the following:
$scope.table = function () {
SpringDataRestService.get(
{
collection: "school",
resource: $scope.teacherSelected.id
},
function (response) {
var students= [];
for (var j = 0; j < response.students.length; j++) {
var entitlement= {
student: response[j].student,
};
students.push(entitlement);
}
$log.info(JSON.stringify(entitlement))
$scope.tableOptions = new NgTableParams({}, {
dataset: students,
counts: []
});
}
);
};
There is an error in for loop. Instead of:
student: response[j].student
you need to use this:
student: response.students[j].student
Check this working demo: DEMO
Related
I want to get specific data from JSON array in adonisjs. But I have some problem to get that data. When I'm looping this JSON array the return just only empty array = []. This is my controller code:
const detail= await TrxHistory.query()
.where('id_trx', params.id_trx)
.fetch()
This return json array:
[
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_confirm",
"created_at": "2019-10-18 22:27:54"
},
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_process",
"created_at": "2019-10-18 22:29:48"
},
]
And i'm try to get data from row "trx_status", using looping like this:
let data = [];
for(var i = 0; i < detail.length; i++) {
data[i] = detail[i]["trx_status"];
}
console.log(data);
What's wrong with this code?
When you fetch adonis lucid request you need to use .rows. Like:
... // Your query
let fooData = [];
detail.rows.forEach(de => {
fooData.push(el.trx_status)
})
How to use?
detail.rows[1]
detail.rows.length
If detail has a structure that you've shown, then it should work perfectly:
const detail = [
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_confirm",
"created_at": "2019-10-18 22:27:54"
},
{
"id_trx_history": "1",
"id_trx": "3",
"trx_status": "shop_process",
"created_at": "2019-10-18 22:29:48"
},
];
let data = [];
for (let i = 0; i < detail.length; i++) {
data[i] = detail[i]["trx_status"];
}
console.log(data);
// another way:
let fooData = [];
detail.forEach(el => {
el["trx_status"] ? fooData.push(el["trx_status"]) : null;
});
console.log(fooData);
"results": {
"code": "SUCCESS",
"msg": [
{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}
]
},
this is my example code,where ever we have \n consider as header elements of table and \t consider as tr elements,can you provide me any suggestion.
You might be looking something like this. In your HTML code right one ng repeat for head and other for each row of the table.
var result = {
"code": "SUCCESS",
"msg": [{
"type": "TABLE",
"data": "id\tfirstname\tlastname\n1\tJack\tSmith\n2\tAdam\tJohnson\n3\tKim\tSmith\n4\tDavid\tWilliams\n5\tPeter\tDavis\n6\tJack\tSmith\n7\tAdam\tJohnson\n8\tKim\tSmith\n9\tDavid\tWilliams\n10\tPeter\tDavis\n11\tPeter\n31\tJack\tSmith\n32\tAdam\tJohnson\n33\tKim\tSmith\n34\tDavid\tWilliams\n35\tPeter\tDavis\n"
}]
}
var format = result.msg.map((r) => {
var str = r.data;
var arr = str.split('\n');
var head = arr.splice(0, 1)[0].split('\t');
arr.pop(); // remove empty string
var data = arr.map((d) => {
return d.split('\t').reduce((obj, x, index) => {
obj[head[index]] = x;
return obj;
}, {})
})
return {
head,
data
}
});
console.log(format);
I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name
I've an array that contains assignments of employees on tasks, it looks like something like this:
$scope.assignments = [
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Kill everyone", project:"Destruction"
},
date: {
day:"01/01", year:"1985"
}
},
{
employee: {
id:"2", firstname:"Luke", lastname:"Skywalker"
},
task: {
name:"Find daddy", project:"Star Wars"
},
date: {
day:"65/45", year:"1000000"
}
},
{
employee: {
id:"1", firstname:"John", lastname:"Rambo"
},
task: {
name:"Save the world", project:"Destruction"
},
date: {
day:"02/01", year:"1985"
}
}
];
I would like to group by employee, for having something like this:
$scope.assignmentsByEmployee = [
{ //First item
id:"1",
firstname:"John",
lastname:"Rambo",
missions: [
{
name:"Kill everyone",
date:"01/01",
year:"1985"
},
{
name:"Save the world",
date:"02/01",
year:"1985"
}
]
},
{ //Second item
id="2",
firstname:"Luke",
lastname:"Skywalker",
missions: [
name:"Find daddy",
date:"65/45",
year:"1000000"
]
}
];
Is their a simple way to do this ? I tried something with a double forEach, but it leads me nowhere.
Hope I'm understandable :)
Thanks !
You should just be able to loop through the assignments array and create a 'keyed array' (which just means using an object in JavaScript) on employee ID. Then you just fill up the missions array as required.
Something like
// initialise a holding object
var assignmentsByEmployee = {};
// loop through all assignemnts
for(var i = 0; i < $scope.assignments.length; i++) {
// grab current assignment
var currentAssignment = $scope.assignments[i];
// grab current id
var currentId = currentAssignment.employee.id;
// check if we have seen this employee before
if(assignmentsByEmployee[currentId] === undefined) {
// we haven't, so add a new object to the array
assignmentsByEmployee[currentId] = {
id: currentId,
firstname: currentAssignment.employee.firstname,
lastname: currentAssignment.employee.lastname,
missions: []
};
}
// we know the employee exists at this point, so simply add the mission details
assignmentsByEmployee[currentId].missions.push({
name: currentAssignment.task.name,
date: currentAssignment.date.day,
year: currentAssignment.date.year
});
}
These leaves assignmentsByEmployee as an object, but you can simply foreach through it and convert it back to an array if required. E.g:
$scope.assignmentsByEmployee = [];
for(var employeeId in assignmentsByEmployee) {
$scope.assignmentsByEmployee.push(assignmentsByEmployee[employeeId]);
}
I got a Json file like;
{
"Cities": [
{
"Name": "London",
"Country": "UK"
},
{
"Name": "Rome",
"Country": "ITA"
},
{
"Name": "Antalya",
"Country": "TR"
}
]
}
How can I get City Names as an array like ["London","Rome","Antalya"] without doing;
var tempJSON = JSON.parse(jsonCities);
var arrayCityNames = [];
for (var i = 0; i < tempJSON.Table.length; i++){
arrayCityNames[i] = tempJSON.Table[i].Name;
}
if tempJSON was a Dataset we could use getColumnArray
arrayCityNames = Data.Dataset.getColumnArray("Name");
Is there any built in method to do this for parsed JSON's?
Please keep in mind that the question is related to Smartface.io Framework, not jquery itself
Try this:
var tempJSON = JSON.parse(jsonCities);// here you load your JSON
var arrayCityNames = []; // your output array
var cityArray = tempJSON['Cities']; // enter Cities array
for (var i = 0; i <cityArray.length; i++){ // iterate over your list
arrayCityNames.push(cityArray[i]['Name']); // add to list name of your city list
}