How to display the output in Tree structure by matching the parent? - angularjs

How can I get the output in tree structure by matching the parent? I can only use a single ng-repeat to display this.
My expected output
firstname :-dsfsdf
lastname :- fdsfsdfs
account:
role:-dsfsdf
status:-dsfdfsfds
js
var app = angular.module("test",[]);
app.controller("MainCtrl",function($scope){
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
{"status" : "Test4"},
]
},
{
"ending" : "yes"
}
];
/*$scope.person = [];*/
$scope.myPersonObj = [];
$scope.checkIndex1 = function(arg, myPersonObj)
{
if (angular.isArray(arg) || angular.isObject(arg)) {
angular.forEach(arg, function (value, key) {
console.log(value + "started");
if(angular.isObject(value) || angular.isArray(value))
{
$scope.checkIndex1(value, myPersonObj);
}
else
{
console.log( value + "pushing--test");
myPersonObj.push(arg);
}
});
}
else
{
console.log( value + "pushing1");
myPersonObj.push(arg);
}
}
$scope.checkIndex1($scope.inputs, $scope.myPersonObj);
console.log("myPersonObj :"+ JSON.stringify($scope.myPersonObj));
console.log($scope.inputs[2] + "del");
}):

Related

AngularJS count matching occurrences in an array

Objective: I want to count the occurrences of an id matching between arrays
The code below finds the match but we need to count the result
var arr1 = [
{
"image" : "FF815_1.jpg",
"id" : "NO"
}, {
"image" : "FF815_0.jpg",
"id" : "NO"
}, {
"image" : "FF815_4.jpg",
"id" : "NO"
}, {
"image" : "PIOJD_2.jpg",
"id" : "NO"
}, {
"image" : "PIOJD_4.jpg",
"id": "JD"
} ];
var arr2 = [
{
"image" : "FF815_1.jpg",
"id" : "NO"
}, {
"image" : "FF815_0.jpg",
"id" : "NO"
}, {
"image" : "FF815_4.jpg",
"id" : "NO"
}, {
"image" : "PIOJD_2.jpg",
"id" : "JD"
}, {
"image" : "PIOJD_4.jpg",
"id" : "JD"
} ];
angular.forEach(arr1, function(value1, key1) {
angular.forEach(arr2, function(value2, key2) {
if (value1.id === value2.id) {
console.log(value2.id);
}
});
});
Heres a fiddle: https://jsfiddle.net/62s0ae7v/
Just add a simple counter like :
var counter = 0;
angular.forEach(arr1, function(value1, key1) {
angular.forEach(arr2, function(value2, key2) {
if (value1.image === value2.image) {
console.log(value2.image);
counter++;
}
});
});
console.log(counter);

Mongodb Aggregate With Deep Nested Array

Hello I tried to querying json data with mongo db with aggregate framework but get stuck, here's the data :
[{
"_id" : ObjectId("5adf2294bc832359aa9bc710"),
"kabupaten" : "Badung",
"jenis_wisata" : [
{
"jenis" : "resto",
"list" : [
{
"nama_resto" : "Warung Nasi Ayam Bu Oki",
"alamat" : "Bukit Jimbaran"
},
{
"nama_resto" : "Warung Pojok Segitiga Emas",
"alamat" : "Bukit Jimbaran"
}
]
},
{
"jenis" : "gunung",
"list" : [
{
"nama_gunung" : "gunung_1",
"alamat" : "alamat_1"
},
{
"nama_gunung" : "gunung_1",
"alamat" : "alamat_1"
}
]
}
]
},{
"_id" : ObjectId("5adf2294bc832359aa9bc711"),
"kabupaten" : "Denpasar",
"jenis_wisata" : [
{
"jenis" : "resto",
"list" : [
{
"nama_resto" : "Warung Nasi Ayam Bu Oki",
"alamat" : "Bukit Jimbaran"
},
{
"nama_resto" : "Warung Pojok Segitiga Emas",
"alamat" : "Bukit Jimbaran"
}
]
},
{
"jenis" : "gunung",
"list" : [
{
"nama_gunung" : "gunung_1",
"alamat" : "alamat_1"
},
{
"nama_gunung" : "gunung_1",
"alamat" : "alamat_1"
}
]
}
]
}]
what I want to achieve is to display the total amount of array "list" inside each element in array "jenis_wisata", here's the expected result that I want to achieve:
[{
"kabupaten" : "Badung",
"jenis_wisata" : [
{
"jenis" : "resto",
"total" : 2
},
{
"jenis" : "gunung",
"total" : 2
}
]
},{
"kabupaten" : "Denpasar",
"jenis_wisata" : [
{
"jenis" : "resto",
"total" : 2
},
{
"jenis" : "gunung",
"total" : 2
}
]
}]
Really appreciate your help here, Thanks
You need $map to transform your inner array and $size to get the length of an array.
db.collection.aggregate([
{
$project: {
kabupaten: 1,
jenis_wisata: {
$map: {
input: "$jenis_wisata",
as: "element",
in: {
jenis: "$$element.jenis",
total: { $size: "$$element.list" }
}
}
}
}
}
])

Aggregation does not working in Mongoose with Match and Group

i'm coding an application using AngularJS, NodeJS and Mongoose.
Now, i'm doing a chart and I need to return some data passsing some parameters.
But the aggregation does not work. I have this query working in MongoDB:
var user = db.getCollection('users').find(
{profile: "SUPERVISOR"},{_id: 1}).map(function(u){return u._id;}
)
db.getCollection("visitas").aggregate(
{ '$match':
{ createdAt:
{ '$gte': ISODate('2015-01-10T00:00:00.000Z'),
'$lt': ISODate('2015-07-01T00:00:00.000Z') } } }, { '$group':
{ _id: { usuario: user, dia: [Object] },
visitas: { '$sum': 1 } } }
)
When I try to run the same query in my application using Mongoose, the query does not work. The problem i've seen is that the comma between MATCH and GROUP is disapearing. When i try to search with only group or match, the query works. Someone can help me? This is the application code:
.then(function (listaUsuarios){
var argsVisit;
console.log({ $match : { "createdAt" : { $gte: "2015-01-10T00:00:00.000Z", $lt: "2015-07-01T00:00:00.000Z" }} },
{ $group : { _id : { "usuario" : listaUsuarios , "dia" : { $dayOfMonth : "$createdAt" } }, "visitas" : { $sum : 1 } } });
Visita.aggregate({ $match : { "createdAt" : { $gte: "2015-01-10T00:00:00.000Z", $lt: "2015-07-01T00:00:00.000Z" }} },
{ $group : { _id : { "usuario" : listaUsuarios , "dia" : { $dayOfMonth : "$createdAt" } }, "visitas" : { $sum : 1 } } })
.exec(function (err, results) {
if (err) {
console.log("Erro!!!");
deferredDados.reject({
error: 500,
message: 'Erro buscando Visita, erro: '+err
});
} else {
if (!results || results.length == 0) {
console.log("Sem retorno!!!");
deferredDados.resolve( [0,0,0,0,0,0,0] ); //Tudo zerado poruqe não há retorno.
//deferredDados.resolve(0);
deferredDados.reject({
error: 500,
message: 'Erro buscando Visitas, não achou resultados'
});
} else {
console.log("Dados"+results);
deferredDados.resolve( results );
//deferredDados.resolve( results.data] );
}
}
});
return deferredDados.promise;
})
SOLVED!!!
A member of my team found the error! \o/
Maybe this can help someone who will have the same problem.
To solve, you just have to convert the date, in string, to the date type.
The solved code is below:
.then(function (listaUsuarios){
var argsVisit;
if (tipoVisita == 'N'){
argsVisit = {'user' : { "$in" :listaUsuarios }, 'tipo' : { "$in" : ["2001","2002"] }, "createdAt": {"$gte": dataInicial, "$lt": dataFinal }};
} else if (tipoVisita == 'R'){
argsVisit = {'user' : { "$in" :listaUsuarios }, 'tipo' : { "$in" : ["2005"] }, "createdAt": {"$gte": dataInicial, "$lt": dataFinal }};
} else if (tipoVisita == 'I'){
argsVisit = {'user' : { "$in" :listaUsuarios }, 'tipo' : { "$in" : ["2003"] }, "createdAt": {"$gte": dataInicial, "$lt": dataFinal }};
}
var initDate = new Date('2015-04-02T00:00:00.000Z');
var endDate = new Date('2015-05-09T00:00:00.000Z');
argsMatch = [{ $match : { "createdAt" : { $gte: initDate, $lt: endDate }} },
{ $group : { _id : { "usuario" : listaUsuarios , "dia" : { $dayOfMonth : "$createdAt" } }, "visitas" : {$sum : { $cond: [ {$or : [ { $eq: [ "$tipo", "2001"] },{ $eq: [ "$tipo","2002"] }] },1,0 ]}}}
}]
Visita.aggregate(argsMatch)
.exec(function (err, results) {
if (err) {
console.log("Erro!!!");
deferredDados.reject({
error: 500,
message: 'Erro buscando Visita, erro: '+err
});
} else {
if (!results || results.length == 0) {
console.log("Sem retorno!!!");
deferredDados.resolve( [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ); //Tudo zerado poruqe não há retorno.
//deferredDados.resolve(0);
deferredDados.reject({
error: 500,
message: 'Erro buscando Visitas, não achou resultados'
});
} else {
deferredDados.resolve( results );
}
}
});
return deferredDados.promise;
})
.then(function(dados) {
res.json(dados);
})
.catch(function(fallback) {
console.log('Erro no retorno dos usuarios!!!');
console.log(fallback);
});
I hope this can help someone.

How can I query in firebase using angularFire?

I have a simple structure in Firebase:
{
"categorias" : {
"categoria2" : {
"subcategorias" : {
"subcategoria4" : {
"nome" : "Subcategoria 4"
},
"subcategoria6" : {
"nome" : "Subcategoria 6"
},
"subcategoria5" : {
"nome" : "Subcategoria 5"
}
},
"icone" : "fa-cloud",
"nome" : "Categoria 2"
},
"categoria1" : {
"subcategorias" : {
"subcategoria1" : {
"nome" : "Subcategoria 1"
},
"subcategoria3" : {
"nome" : "Subcategoria 3"
},
"subcategoria2" : {
"nome" : "Subcategoria 2"
}
},
"icone" : "fa-bolt",
"nome" : "Categoria 1"
}
},
"locais" : {
"local1" : {
"subcategorias" : {
"subcategoria4" : true,
"subcategoria1" : true
},
"nome" : "Local 1",
"email" : "local1#loc1.com"
}
}
}
I need to list all "locais" that have "subcateria1: true" for example. I don't know how to do this because it is need "localId" but in query I don't know the localId. I just want all the "locais" that belongs to subcategoria1.
I'm using AngularFire.
I find the solution, but i don't know if it is the right way:
findBySubcategoria: function(subcategoriaId) {
var result = {};
locais.$on("value", function(snap){
var keys = snap.snapshot.value;
angular.forEach(keys, function(key, i){
if(key.subcategorias[subcategoriaId]){
result[i] = locais.$child(i);
}
});
});
return result;
}

MongoDB find the intersection of arrays

docs:
order1.filter = ['tag1','tag2']
order2.filter = ['tag1','tag2','tag3']
want to get:
query ['tag1','tag2'] -> (only order1)
query ['tag1','tag2','tag3'] -> (order1 and order2)
query ['tag1','tag2','tag3','tag4', etc ] -> (order1 and order2)
and
query ['tag1','tag3'] -> (null)
query ['tag2','tag3'] -> (null)
All values ​​order.filter should be necessarily in the query array
How to do it? Tried directives $all, $in :(
You can do this with aggregation framework (there is no way to do this with regular find that I know of).
I think this is basically a duplicate so adjusting that code for your fields you get something like:
//sample documents:
> db.docs.find({},{_id:0})
{ "order" : 1, "filter" : [ "t1", "t2" ] }
{ "order" : 2, "filter" : [ "t1", "t2", "t3" ] }
var tagArray = [ "t1", "t2" ]; // array to "match"
db.docs.aggregate( [
{
"$project" : {
"order" : 1,
"filter" : 1,
"killFlag" : {
"$const" : [
true,
false
]
}
}
},
{
"$unwind" : "$filter"
},
{
"$unwind" : "$killFlag"
},
{
"$match" : {
"$nor" : [
{
"filter" : {
"$in" : tagArray
},
"killFlag" : true
}
]
}
},
{
"$group" : {
"_id" : "$order",
"filter" : {
"$addToSet" : "$filter"
},
"killFlag" : {
"$max" : "$killFlag"
}
}
},
{
"$match" : {
"killFlag" : false
}
},
{
"$project" : {
"_id" : 1,
"filter" : 1
}
}
]);

Resources