This question already has answers here:
Get the last item in an array
(59 answers)
Closed 6 years ago.
I have JSON object from server and requirement is to always display last item from the array items. how can i achieve that task using AngularJs or native JavaScript ?
Below case i have to display text Chief Administrative Officer.
main.js
angular.forEach($scope.rcsaErhTreeData, function(val) {
angular.forEach(val, function(val) {
console.log('this is the array value', val[0].text);
});
});
json.js
[{
"uid": null,
"index": 0,
"selected": null,
"expanded": null,
"id": 2701,
"text": "BAC Enterprise Wide",
"parentId": 0,
"items": [{
"uid": null,
"index": 0,
"selected": null,
"expanded": null,
"id": 4114,
"text": "Chief Administrative Officer",
"parentId": 2701,
"items": []
}]
}]
if you try the following code in your context you will get the result.
console.log(JSON.stringify(items[items.length - 1]));
The console will show you the stringified output...
Thanks,
Paras
I am not a Angular.js programmer, but the concept would be to:
1. Either do it in a loop and overwrite the variable value with the next value, that way, the last one will persist. -- Not recommended due to performance issues, and using a loop when it can be done without a loop.
Pseudo code:
var outVal='';
angular.forEach($scope.rcsaErhTreeData, function(val) {
angular.forEach(val, function(val) {
outVal = val[0].text);
});
});
console.log('this is the last item value', outVal);
Another approach would be find the length of the val array, and go to its last index to fetch its value. I am not a pro in this language so cannot give an example code. Sorry about that.
Related
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 months ago.
This post was edited and submitted for review 4 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I add a json value from a response to a variable and then print it this way result: ${JSON.stringify(result)}, but what i want exactly is to get only one exact value from this json
here's the json
{
"flags": [
{ "flagID": "0f0571b5-af7b-48e2-8418-044cbec0166d", "flagname": "lionsflag", "team": "lions", "membersnum": "4", "win": false },
{ "flags": "9819c0bd-e134-4950-a1ee-7f89450ee4b6", "flagname": "Barcaflag", "membersnum": "4", "win": true }
]
}
I only want to extract lionsflag string only from the first flagname, this value is able to change any time
You need to use Object.keys() to get all the keys and then check the related value is meet your demand or not
let data = {
"flags": [
{ "flagID": "0f0571b5-af7b-48e2-8418-044cbec0166d", "flagname": "lionsflag", "team": "lions", "membersnum": "4", "win": false },
{ "flags": "9819c0bd-e134-4950-a1ee-7f89450ee4b6", "flagname": "Barcaflag", "membersnum": "4", "win": true }
]
}
let value = "lionsflag"
data.flags.filter(d => Object.keys(d).forEach(e =>{
if(d[e] == value){
console.log(e + ";" + value)
}
}))
let prop ='flagname'
console.log(data.flags[0][prop])
first time question asker.
I am working on trying to bring together data from two different API endpoints being served from a Django Rest Framework backend and rendering the display with VueJS on the frontend.
The challenge I am faced with is merging my questionnaire sections and questions with the associated answers. The questionnaire information is coming from one endpoint and the answers from another. Below is a sample of the data.
Sections & Questions Data
{
"survey_id": 2,
"survey_name": "My Survey",
"instructions": "Instructions.",
"other_header_info": ""
"section": [
{
"section_id": 2,
"section_name": "Section Name",
"section_title": "Section Title",
"section_instructions": "Some Instructions",
"section_required_yn": true,
"question": [
{
"question_id": 2,
"question_name": "Question One.",
"question_subtext": "None.",
"answer_required_yn": true,
"input_type_id": {
"id": 3,
"input_type_name": "Dropdown"
},
"option_group_id": "1 - 10",
"allow_multiple_option_answers_yn": false
},
{
"section_id": 3,
"section_name": "Another Section",
"section_title": "Section Title",
"section_instructions": "Section Instructions",
"section_required_yn": true,
"question": [
{
"question_id": 10,
"question_name": "Another question to be answered",
"question_subtext": "None.",
"answer_required_yn": true,
"input_type_id": {
"id": 3,
"input_type_name": "Dropdown"
},
"option_group_id": "1 - 10",
"allow_multiple_option_answers_yn": false
},
Answers Data
"results": [
{
"id": 100,
"answer_numeric": 4,
"answer_text": null,
"answer_yn": null,
"answer_group": "4-ojepljuu",
"question_id": 2,
},
{
"id": 101,
"answer_numeric": 1,
"answer_text": null,
"answer_yn": null,
"answer_group": "4-ojepljuu",
"user_id": 4,
"question_id": 5,
},
I know I need to match up the question_id fields from both the questionnaire sections data and the answers data. The problem I am facing is, how does one go about doing this?
I would like to create a new set of data that appends the answer data to the question data. I am also trying to build in some flexibility since I have multiple survey types with a variable number of sections and questions.
Trying to keep the data in sections so I can render the frontend views the way I would like.
I've tried looping through sections and questions, using the example I found here: Merge two array of objects based on a key but haven't had much luck.
Still relatively new - any information, guidance or even a working example would be greatly appreciated.
Update:
I've managed to make a bit of progress on this. Writing a small test function, I can now update the section/question object with some dummy data.
var a = this.answers;
var s = this.section;
var newObj = { answer_text: "test1", answer_numeric: "test2" };
for (var idx3 = 0; idx3 < s.length; idx3++) {
for (var idx4 = 0; idx4 < s[idx3].question.length; idx4++) {
Object.assign(s[idx3].question[idx4], newObj);
}
}
Each of the question objects within each section now includes the answer_text and answer_numeric key/value pairs.
The next challenge is to find the matching answer data based on matching the appropriate question_id within the answer object to the question_id in the question object.
Any thoughts?
I would store results as a dictionary, instead of an array:
var results_to_dict = function (results) {
var dict = {};
results.forEach(r => dict[r.question_id] = r);
return dict;
};
results = results_to_dict(results);
Now, you can show your questions in your template with their answers:
<div v-for="question in section.questions" :key="question.question_id">
<p>Question: {{question.question_name}}</p>
<p>Answer: {{answers[question_id].text}}</p>
</div>
I want to create a JSON API that returns a list of objects. Each object has an id, a name and some other information. API is consumed using JavaScript.
The natural options for my JSON output seems to be:
"myList": [
{
"id": 1,
"name": "object1",
"details": {}
},
{
"id": 2,
"name": "object2",
"details": {}
},
{
"id": 3,
"name": "object3",
"details": {}
},
]
Now let's imagine that I use my API to get all the objects but want to first do something with id2 then something else with id1 and id3.
Then I may be interested to be able to directly get the object for a specific id:
"myList": {
"1": {
"name": "object1",
"details": {}
},
"2": {
"name": "object2",
"details": {}
},
"3": {
"name": "object3",
"details": {}
},
}
This second option may be less natural when somewhere else in the code I want to simply loop through all the elements.
Is there a good practice for these use cases when the API is used for both looping through all elements and sometime using specific elements only (without doing a dedicated call for each element)?
In your example you've changed the ID value from 1 to id1. This would make operating on the data a bit annoying, because you have to add and remove id all the time.
If you didn't do that, and you were relying on the sorted order of the object, you may be in for a surprise, depending on JS engine:
var source = JSON.stringify({z: "first", a: "second", 0: "third"});
var parsed = JSON.parse(source);
console.log(Object.keys(parsed));
// ["0", "z", "a"]
My experience is to work with arrays on the transport layer and index the data (i.e. convert array to map) when required.
I'm new to JS an this is likely a noob question, but I can't seem to find an answer which I figure may be due to my lack of correct terminology.
Basically I'm trying to count how many "active" fields in a JSON file are set to true vs false and return those values to a variable. I'm just getting lost trying to figure out how to go about this.
For example, my JSON is named data and looks like this:
{
"systems": [
{
"name": "SV001",
"IP": "10.1.1.101",
"active": "true"
},
{
"name": "SV002",
"IP": "10.1.1.102",
"active": "true"
},
{
"name": "SV003",
"IP": "10.1.1.103",
"active": "false"
}
]}
Any help would be greatly appreciated.
You could parse into the json object from string like
var json=JSON.parse(jsonString); And than by looping you can get the value.
var count=0;
for(var i=0i<json.systems.length;i++){
if(json.systems[i].active){
count++;
}
}
you can have count at the end of loop.
I want to create a array structure with child entities like this ->
$scope.groups = [
{
"categories": [
{
"name": "PR",
"sortOrder": 0,
"type": "category"
}
],
"name": "DEPT 1",
"sortOrder": 0,
"type": "group",
"id": "-JY_1unVDQ5XKTK87DjN",
"editing": false
}
];
from an array that dosen't have child entities but all the items are listed in one object like this->
$scope.groups = [
{
"name": "PR",
"sortOrder": 0,
"type": "category"
},
{
"name": "AD",
"sortOrder": 3,
"type": "category"
},
{
"name": "DEPT 2",
"sortOrder": 1,
"type": "group",
"id": "-JYZomQKCVseJmaZoIF9",
"editing": false,
"categories": []
},
];
Is there any possible way?
As #Eagle1 has rightly pointed out. You need to define your data model properly to define a function that does that grouping for you. That said, from what I understand you have a $scope.groups array of objects for a specific department containing some categories which you need to consolidate as a child element.
You could start by defining a function that returns an object like you mention:
var organize = function(arr){
cats = [];
dep = {};
$.each( arr, function( i, val ) {
if(val.type == "category")
cats.push(val);
else
dep = val;
});
dep.categories = cats;
return dep;
}
Ultimately, you'll have to traverse the array and look for objects of type category and dump them in an array and have that array as the categories key of the object that you intend to return. I hope it gets you started in the right direction.
of course it is.
It's doable in javascipt although to help you devise something we would need a relationship between categories.
However, that's sounds like something that should be done in your data model (a relationship between dept - category, classic reflexive relationship parent - children). angular should be receiving from the back end an array already ordered.