Backend sends an object that contains an array of objects. These objects contain more arrays of objects and so on. It resembles a tree.
I need to be able to go from one object to the other, following the array, and back. What would be the best way to do this in typescript?
I tried forEach, but I couldn't go back. For cycles inside of for cycles aren't an option either because sometimes there will be 2 levels of arrays, sometimes, 5. I thought of an iterator, but I don't know enough of angular/typescript to make it happen.
Here is a snippet of the data. This is a questionnaire and I need to show each question individually.
"questionId": 1,
"parent": null,
"description": "Question 1?",
"children":
[
{
"questionId": 2,
"parent": 1,
"description": "Question 2?",
"children":
[
{
"questionId": 4,
"parent": 2,
"description": "Question 4?",
"children": []
}
]
},
{
"questionId": 3,
"parent": 1,
"description": "Question 3?",
"children": []
}
]
Sorry if I'm explaining it poorly or something is missing, I'm not used to post here.
If you just want to iterate through all the question objects, you could try to flatten your data with a recursive function like this,
const flattenQs = (qData) => {
const flattenedQs = []
flattenedQs.push({questionId: qData.questionId, parent: qData.parent, description: qData.description})
for (let i = 0; i < qData.children.length; i++) {
const qChild = qData.children[i];
flattenedQs.push(...flattenQs(qChild))
}
return flattenedQs
}
Which would give something like this,
[
{
questionId:1,
parent:null,
description:"Question 1?"
},
{
questionId:2,
parent:1,
description:"Question 2?"
},
{
questionId:4,
parent:2,
description:"Question 4?"
},
{
questionId:3,
parent:1,
description:"Question 3?"
}
]
Related
I want to get an output as an unique set of Categories array with the following output [Men,Woman].
Is there any way to do it in Javascript?
For example this my data
{
"products:"[
{
"id": 1,
"categories": {
"1": "Men",
},
},
{
"id": 2,
"categories": {
"1": "Men",
},
}, {
"id": 3,
"categories": {
"1": "Woman",
},
}
];
}
A simple 1 line answer would be
new Set(input.products.map(p => p.categories["1"]))
This is if you're expecting only key "1" in the categories object.
If it can have multiple categories then you can always do
const uniqueCategories = new Set();
input.products.forEach(p => uniqueCategories.add(...Object.values(p.categories)))
Now you can convert a Set into an array
PS: This is not a ReactJs problem but a pure JS question. You might want to remove the ReactJs tag from this question altogether.
I want to take items from this array (the way I save things on the client)
[
{
"id": "-Mdawqllf_-BaW63gMMM",
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800
},
{
"id": "-Mdawqllf_-BaW63gGHf",
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000
},
{
"id": "-Mdawqllf_-BaW63gGHd",
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000
}
]
And turn them into this format for how I save it server side
{ "todos": {
"-Mdawqllf_-BaW63gMMM": {
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800,
},
"-Mdawqllf_-BaW63gGHf": {
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000,
},
"-Mdawqllf_-BaW63gGHd": {
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000,
}
},
}
Basically i turn items into an array on the client to help with sorting and making use of arrays. But before sending it back need to put into the right format
Use .map() to loop over the array of objects to exctract the id property, so you can use it as the key of the new object.
Use Object.fromEntries() to create the new object from the array returned by .map().
const data = [
{
"id": "-Mdawqllf_-BaW63gMMM",
"text": "Finish the backend[1]",
"status": true,
"time": 1625248047800
},
{
"id": "-Mdawqllf_-BaW63gGHf",
"text": "Finish the middle-end[2]",
"status": false,
"time": 1625248040000
},
{
"id": "-Mdawqllf_-BaW63gGHd",
"text": "Finish the front-end[3]",
"status": false,
"time": 1625248040000
}
];
const todos = {
Todos: Object.fromEntries(data.map(obj => [obj.id, obj]))
};
console.log(todos);
#Barmar's solutions is nice.
For the sake of learning or others googling. You can also reduce the array to an object.
const todos = data.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
const items = {
todos: {
...data
}
};
Assume that data is the array of objects.
Use the spread operator to copy all the array objects from data array to the todos object at key todos.
One important thing to note that you can't assign more than one objects without array to a single object key. You definately have to use the array to maintain all the objects under the one key.
Avoid using the hardcode index. Always use the spread operator
I got JSON data, like:
{
"id": 1,
"active": true,
"dependency": [
{ "id": 2 }
{ "id": 3 }
]
},
{
"id": 2,
"active": true
},
{
"id": 3,
"active": true
}
I want to retrieve the "active" value for each dependency in the id 1 object. So far I used a forEach to get those dependency.
thisElement.dependency.forEach(function(id) {
console.log(id)
}
Which returns id 2 and id 3 as objects. Is there a way to use id.active straight away? By using only one loop? Because the result so far are objects without any connection to the related JSON data. Would it require to loop through the whole JSON data to retrieve those values?
The most efficient thing to to is create a hashmap with an Object or Map first so you only need to iterate the array once to find dependency related values.
You could do it by using Array#find() to search whole array each time but that is far more time complexity than the o(1) object lookup
const activeMap = new Map(data.map(obj => [obj.id, obj.active]))
data[0].dependency.forEach(({id}) => console.log(id ,' active: ' , activeMap.get(id)))
<script>
const data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2 },
{"id": 3}
]
},
{
"id": 2,
"active": false
},
{
"id": 3,
"active": true
}
]
</script>
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.