Working with fetched Firebase data - javascript

How do I get the keys "-KTjDx_Ms255rS7GGT7l" for my returned objects so I can access nested data? The data being returned to me from Firebase is one big object containing other objects. It looks like this.
{
"-KTjDx_Ms255rS7GGT7l": {
"questions": [
{
"options": [
{ "isAnswer":false,"text":"dfsf"} , {"isAnswer":false,"text":"fffffff"} , {"isAnswer":false,"text":"fsfsdfs"}
],
"text":"sdfsf"
}
]
},
{
"-KTjDx_Ms255rS7GGT7l": {
"questions": [
{
"options": [
{ "isAnswer":false,"text":"dfsf"} , {"isAnswer":false,"text":"fffffff"} , {"isAnswer":false,"text":"fsfsdfs"}
],
"text":"sdfsf"
}
]
},
{
"-KTjDx_Ms255rS7GGT7l": {
"questions": [
{
"options": [
{ "isAnswer":false,"text":"dfsf"} , {"isAnswer":false,"text":"fffffff"} , {"isAnswer":false,"text":"fsfsdfs"}
],
"text":"sdfsf"
}
]
},

Let's assume your data is called firebaseResponse:
Object.keys( firebaseResponse ).forEach( function( key ) {
var item = firebaseResponse[ key ];
item.questions ...
});

Related

Using Array.map in nested object structure in Java Script

I have below object structure in array
[
{
"modules":set of modules here
"details": [
{
"name":"abc"
"version":"1.2.3"
},
{
"name":"def"
"version":"2.3.4"
},
{
"name":"ghi"
"version":"4.5.6"
}
]
},
{
"modules":set of modules here
"details": [
{
"name":"jkl"
"version":"7.8.9"
},
{
"name":"mno"
"version":"10.11.12"
},
{
"name":"pqr"
"version":"13.14.15"
}
]
}
]
What I want to do is :
get details array transformed into below format for each root object in master array as
"details": [
{
module:"jkl:7.8.9"
},
{
module:"mno:10.11.12"
},
{
module:"pqr:13.14.15"
}
]
So final array would be :
[
{
"modules":set of modules here
"details": [
{
"module":"abc:1.2.3"
},
{
"module":"def:2.3.4"
},
{
"module":"ghi:4.5.6"
}
]
},
{
"modules":set of modules here
"details": [
{
"module":"jkl:7.8.9"
},
{
"module":"mno:10.11.12"
},
{
"module":"pqr:13.14.15"
}
]
}
]
What I have tried and is working is :
rootArray.forEach((entry)=> {
let line = entry.details.map((detailEntry)=>{
//merge detailEntry into single line
})
entry.details = line
});
My question is : is this a right approach or is there any better solution available ?
Two maps is probably the right approach. It will return a new array rather than mutating the original array.
map over the main data array, and then assign the result of mapping over details to the details property of the object that you're returning on each iteration.
const data=[{modules:"set of modules here",details:[{name:"abc",version:"1.2.3"},{name:"def",version:"2.3.4"},{name:"ghi",version:"4.5.6"}]},{modules:"set of modules here",details:[{name:"jkl",version:"7.8.9"},{name:"mno",version:"10.11.12"},{name:"pqr",version:"13.14.15"}]}];
const out = data.map(obj => {
return {
modules: obj.modules,
details: obj.details.map(detail => {
const { name, version } = detail;
return { module: `${name}:${version}` };
})
};
});
console.log(out);
Additional documentation
Destructuring assignment
map
Template/string literals
const data = [
{
"modules": "set of modules here",
"details": [
{
"name":"abc",
"version":"1.2.3"
},
{
"name":"def",
"version":"2.3.4"
},
{
"name":"ghi",
"version":"4.5.6"
}
]
},
{
"modules": "set of modules here",
"details": [
{
"name":"jkl",
"version":"7.8.9"
},
{
"name":"mno",
"version":"10.11.12"
},
{
"name":"pqr",
"version":"13.14.15"
}
]
}
]
const result = data.map( item => ({modules: item.modules, details: item.details.map(i => {
return { module: `${i["name"]}:${i["version"]}` }
})}))
console.log(result)
your approach seems correct.
there is another way to achieve the expected structure, making the copy of the initial array however instead of modifying the existing.
const result = rootArray.map(({ details, ...rest }) => ({
details: details.map(/*transform*/),
...rest
));

How can I sort a javascript array of objects that specify prerequisites between them?

I have an array of objects that determine which ones should be showed first. An example of this array would be:
[
{
"id": "b94ae1a5-c6b2-4e45-87cd-a4036fdb7870",
"prerequisites_ids": [
"2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1"
]
},
{
"id": "ef7d2415-808f-4efc-939e-2692f38a5ee7",
"prerequisites_ids": [
"74e41a2c-e74e-4016-bb2c-f2e84c04fe92"
]
},
{
"id": "74e41a2c-e74e-4016-bb2c-f2e84c04fe92",
"prerequisites_ids": []
},
{
"id": "2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1",
"prerequisites_ids": [
"ef7d2415-808f-4efc-939e-2692f38a5ee7"
]
}
]
How could I sort it to get this?
[
{
"id": "74e41a2c-e74e-4016-bb2c-f2e84c04fe92",
"prerequisites_ids": []
},
{
"id": "ef7d2415-808f-4efc-939e-2692f38a5ee7",
"prerequisites_ids": [
"74e41a2c-e74e-4016-bb2c-f2e84c04fe92"
]
},
{
"id": "2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1",
"prerequisites_ids": [
"ef7d2415-808f-4efc-939e-2692f38a5ee7"
]
},
{
"id": "b94ae1a5-c6b2-4e45-87cd-a4036fdb7870",
"prerequisites_ids": [
"2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1"
]
}
]
I have tried creating a custom function:
export function comparePrerequisites(a, b) {
if (!a.prerequisites_ids) {
return -1
}
if (a.prerequisites_ids.includes(b.id)) {
return 1;
}
}
data.sort(comparePrerequisites)
but does not seem to work. Thanks in advance!
We have here the requirements for a topological sort. This is not a job for the sort method. Instead you can use recursion (a DFS traversal) to drill down to a dependency that is already collected, or to a leaf (no dependencies).
Here is an implementation:
function topologicalSort(tasks) {
const visited = new Set;
const taskMap = new Map(tasks.map(task => [task.id, task]));
function dfs(tasks) {
for (let task of tasks) {
if (!visited.has(task.id)) {
dfs(task.prerequisites_ids.map(id => taskMap.get(id)));
}
visited.add(task);
}
}
dfs(tasks);
return [...visited];
}
// Demo on your example:
let tasks = [{"id": "b94ae1a5-c6b2-4e45-87cd-a4036fdb7870","prerequisites_ids": ["2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1"]},{"id": "ef7d2415-808f-4efc-939e-2692f38a5ee7","prerequisites_ids": ["74e41a2c-e74e-4016-bb2c-f2e84c04fe92"]},{"id": "74e41a2c-e74e-4016-bb2c-f2e84c04fe92","prerequisites_ids": []},{"id": "2a4fdd9c-45d0-49d9-a0eb-ba5a0464f2b1","prerequisites_ids": ["ef7d2415-808f-4efc-939e-2692f38a5ee7"]}];
console.log(topologicalSort(tasks));

How to convert this Array to Object

I can't seem to find the answer, how to change array in array to object in array ..??
problem this in javaScript. How to convert? How to convert?
I have this array.
[
"or",
[
"or",
{
"status": 1
},
{
"verified": 1
}
],
[
"and",
{
"social_account": 1
},
{
"enable_social": 1
}
]
]
I want this object:
{
"or": [
{
"or": [
{
"status": 1
},
{
"verified": 1
}
]
},
{
"and": [
{
"social_account": 1
},
{
"enable_social": 1
}
]
}
]
}
You can use a recursive function. The base case is when the argument is not an array. In the other case, extract the first array value as key for the object, and map the rest of the array via the recursive function:
const convert = data => Array.isArray(data) && ["or","and"].includes(data[0])
? { [data[0]]: data.slice(1).map(convert) }
: data;
// demo:
let data = ["or",
["or", {"status": 1}, {"verified": 1}],
["and",{"social_account": 1}, {"enable_social": 1}]
];
console.log(convert(data));

How to get a keys of nested json object in json heirarchy

I am new to javascript and json.Basically i have to fetch all keys of nested json object in a parent child relationship heirarchy.The keys are dynamic so I won't necessarily know the keys.
for eg. i have a json
{
"Indo-European": {
"Indo-Iranian": {
"Iranian": [
"Persian",
"Avestan",
"Sogdian",
"Baluchi",
"Kurdish",
"Pashto"
],
"Indic": [
"Assamese",
"Bengali",
"Gujarati",
"Hindi",
"Marathi",
"Punjabi",
"Romany",
"Sindhi",
"Singhalese",
"Urdu"
]
},
"Baltic": [
"Latvian",
"Lithuanian"
]
}
}
output must be-
Indo-European
Indo-European.Indo-Iranian
Indo-European.Indo-Iranian.Iranian
Indo-European.Indo-Iranian.Indic
Indo-European.Baltic
You could do something like this, runs in O(n3) time complexity but works
let json = {
"Indo-European": {
"Indo-Iranian": {
"Iranian": [
"Persian",
"Avestan",
"Sogdian",
"Baluchi",
"Kurdish",
"Pashto"
],
"Indic": [
"Assamese",
"Bengali",
"Gujarati",
"Hindi",
"Marathi",
"Punjabi",
"Romany",
"Sindhi",
"Singhalese",
"Urdu"
]
},
"Baltic": [
"Latvian",
"Lithuanian"
]
}
}
let lv1 = Object.keys(json)
lv1.forEach(i => {
console.log(i)
let lv2 = Object.keys(json[i])
lv2.forEach(j => {
console.log(`--${i}*${j}`)
let lv3 = Object.keys(json[i][j])
lv3.forEach(k => {
if (!json[i][j].hasOwnProperty(length)) {
console.log(`----${i}*${j}*${k}`)
}
})
})
})

need to convert complex json obj to suitable angularjs ui tree data json structure

In my angularjs project I have original json in the following format :
$scope.orgJsonObj = {
"parentNodesList":[
"0",
"1",
"1.1",
"2",
"2.2"
],
"childNodes":{
"0":[
"1",
"2"
],
"1":[
"1.1",
"1.2"
],
"1.1":[
"1.1.1"
],
"2":[
"2.1",
"2.2"
],
"2.2":[
"2.2.1",
"2.2.3"
]
},
"nodeDetailsList":[
{
"id":"0",
"name":"node0"
},
{
"id":"1",
"name":"node1",
"parentId":"0"
},
{
"id":"2",
"name":"node2",
"parentId":"0"
},
{
"id":"1.1",
"name":"node1.1",
"parentId":"1"
},
{
"id":"1.2",
"name":"node1.2",
"parentId":"1"
},
{
"id":"1.1.1",
"name":"node1.1.1",
"parentId":"1.1"
},
{
"id":"2.1",
"name":"node2.1",
"parentId":"2"
},
{
"id":"2.2",
"name":"node2.2",
"parentId":"2"
},
{
"id":"2.2.1",
"name":"node2.2.1",
"parentId":"2.2"
},
{
"id":"2.2.3",
"name":"node2.2.3",
"parentId":"2.2"
}
]
}
Now I want to convert orgJsonObj json structure in to the tree structure similar to angular ui tree json data structure. In orgJsonObj, parentNodesList contains all parents in the tree. Each parent's children list is available in childNodes. Each nodes complete information is available in nodeDetailsList. The node obj { "id":"0", "name":"node0"} does not have parentId, property in it because it is the root of the tree.
After conversion my $scope.orgJsonObj, should become as shown below (which is suitable for angularjs ui tree)
$scope.finalJsonObj = [
{
"id":"0",
"title":"node0",
"nodes":[
{
"id":"1",
"title":"node1",
"nodes":[
{
"id":"1.1",
"title":"node1.1",
"nodes":[
{
"id":"1.1.1",
"title":"node1.1.1",
"nodes":[
]
}
]
},
{
"id":"1.2",
"title":"node1.2",
"nodes":[
]
}
]
},
{
"id":"2",
"title":"node2",
"nodes":[
{
"id":"2.1",
"title":"node2.1",
"nodes":[
]
},
{
"id":"2.2",
"title":"node2.2",
"nodes":[
{
"id":"2.2.1",
"title":"node2.2.1",
"nodes":[
]
},
{
"id":"2.2.3",
"title":"node2.2.3",
"nodes":[
]
}
]
}
]
}
]
}
]
Can any one help me in this.
var originalData = {};
var treeData = transformNesting("0", originalData.childNodes);
var result = applyData(treeData, originalData.nodeDetailsList);
function transformNesting(root, nestedData){
var tree = {
id: root,
nodes: nestedData[root] ? nestedData[root].map(function(newRoot){ return transformNesting(newRoot, nestedData)}) : []
};
return tree;
}
function getNodeById(list, id){
return list.filter(function(item){
return item.id === id;
})[0];
}
function applyData(tree, config){
tree.title = getNodeById(config, tree.id).name;
tree.nodes = tree.nodes.map(function(node){return applyData(node, config)});
return tree;
}

Categories