Array filter in angularjs - angularjs

I need to make a filter that searches the following array of objects and filters out those objects whose ID value is equal to a Message value in any of those objects in the array. Also the filter should return only objects with level equal to 1. I've already managed to filter the level property, but I can't seem to figure out how to do the rest.
Let's consider an example: ID: 001 contains in its Message 006, so I want to filter out all objects, whose ID is 006.
$scope.myData = [
{
"ID" : "001",
"Message" : "006",
"level":"1"
},
{
"ID" : "002",
"Message" : "test test test test1",
"level":"1"
},
{
"ID" : "003",
"Message" : "test test test test",
"level":"1"
},
{
"ID" : "004",
"Message" : "test test test test",
"level":"1"
},
{
"ID" : "005",
"Message" : " My Test",
"level":"1"
},
{
"ID" : "006",
"Message" : "",
"level":"1"
},
{
"ID" : "007",
"Message" : "next level",
"level":"2"
}
];
})
And filter:
app.filter('filterData3', function () {
return function (data) {
var dataToBePushed = [];
data.forEach(function (resultData) {
if (resultData.level == 1)
dataToBePushed.push(resultData);
});
return dataToBePushed;
}
});

Assuming that what you want is to NOT include in your filtered array the elements which ID is contained in another element's Message, you could write a filter like the following:
.filter('filterData3', function () {
return function (data) {
var dataToBePushed = [];
var messages =[];
data.forEach(function (resultData) {
if (resultData.level == 1 && (messages.indexOf(resultData.ID) == -1)) {
messages.push(resultData.Message);
dataToBePushed.push(resultData);
}
});
return dataToBePushed;
}})
Hope this works for you

Related

How do I search and return the field and data in a multi-level array of object?

I have a data set returned by find command in MongoDB. How do I search for the value and field of DeviceJson[] in the given data
{ location: [],
_id: 5d42d171e7ceef2a90245470,
farmName: 'Xilo',
description: 'This is test from Postman Api Request',
farmAddDate: 2019-08-01T11:48:01.883Z,
device:
[
{ _id: 5d441878f1877637cc712d07,
deviceName: 'Xki',
deviceType: 'Muc',
description:
'This is test for updation of specific data in a specfic farm .Test Pass',
deviceLocation: [Array],
Parameter: 'Hello Happy',
Topic: 'v1/Xki/11,180/Hello Happy' },
{ _id: 5d4418953968370e64c32e1f,
deviceName: 'Xki',
deviceType: 'Muc',
description:
'This is test for updation of specific data in a specfic farm .Test Pass',
deviceLocation: [Array],
Parameter: 'Hello Happy',
Topic: 'v1/Xki/11,180/Hello Happy' },
{ _id: 5d4425548b3cf92af46e2c9a,
deviceName: 'Xki',
deviceType: 'Muc',
description:
'This is test for updation of specific data in a specfic farm .Test Pass',
deviceLocation: [Array],
Parameter: 'Hello Happy 1',
Topic: 'sagita/5d42d171e7ceef2a90245470/Xki/11,180/Hello Happy 1' },
{ _id: 5d44256d8b3cf92af46e2c9b,
deviceName: ' DeviceX01',
deviceType: ' Test',
description: ' This is a test',
deviceLocation: '11.22,33.12',
Parameter: ' set',
Topic:
'sagita/5d42d171e7ceef2a90245470/ DeviceX01/11.22,33.12/ set',
DeviceJson: [Array] }
]
}
The data Set I have saved in an array called usdData=[] and was looping through its index and this is resultant and I want to search even Interior and the value of DeviceJson in the schema. How can I do so?
var usdData=[];
collection.findOne({"email":Username},function (err,doc) {
if (err) throw err;
usdData=doc.farm;
for (let index = 0; index < usdData.length; index++) {
if (usdData[index].farmName === gotfarmName) {
return usdData[index];
}
const element = usdData[index];
// const dElement = JSON.stringify(element);
// console.log("Array started here \n"+dElement);
// const ddElement= JSON.parse(dElement) ;
console.log(usdData[1]);
}
return console.log();
});
If you known the 'DeviceJson' structure you can do something like this:
01) Example of Document:
{
"_id" : "5d42d171e7ceef2a90245470",
"location" : [],
"farmName" : "Xilo",
"description" : "This is test from Postman Api Request",
"farmAddDate" : "2019-08-01T11:48:01.883Z",
"device" : [
{
"_id" : "5d441878f1877637cc712d07",
"deviceName" : "Xki",
"deviceType" : "Muc",
"description" : "This is test for updation of specific data in a specfic farm .Test Pass",
"deviceLocation" : [],
"Parameter" : "Hello Happy",
"Topic" : "v1/Xki/11,180/Hello Happy"
},
{
"_id" : "5d4418953968370e64c32e1f",
"deviceName" : "Xki",
"deviceType" : "Muc",
"description" : "This is test for updation of specific data in a specfic farm .Test Pass",
"deviceLocation" : [],
"Parameter" : "Hello Happy",
"Topic" : "v1/Xki/11,180/Hello Happy"
},
{
"_id" : "5d4425548b3cf92af46e2c9a",
"deviceName" : "Xki",
"deviceType" : "Muc",
"description" : "This is test for updation of specific data in a specfic farm .Test Pass",
"deviceLocation" : [],
"Parameter" : "Hello Happy 1",
"Topic" : "sagita/5d42d171e7ceef2a90245470/Xki/11,180/Hello Happy 1"
},
{
"_id" : "5d44256d8b3cf92af46e2c9b",
"deviceName" : "DeviceX01",
"deviceType" : " Test",
"description" : " This is a test",
"deviceLocation" : "11.22,33.12",
"Parameter" : " set",
"Topic" : "sagita/5d42d171e7ceef2a90245470/ DeviceX01/11.22,33.12/ set",
"DeviceJson" : [
{
"_id" : "5db85e439a17899b8ba631cd",
"name" : "deviceJsonOne",
"complexObject" : {
"_id" : "5db85e439a17899b8ba631ce"
},
"someArray" : [
{
"someThing" : 1
},
{
"someThing" : 2
}
]
},
{
"_id" : "5dae22702486f7d89ba7633c",
"name" : "deviceJsonTwo",
"complexObject" : {
"_id" : "5db85e439a17899b8ba631cf"
},
"someArray" : [
{
"someThing" : 3
},
{
"someThing" : 2
}
]
}
]
}
]
}
02) Query:
db.Collection.aggregate([
// INITIAL FILTER... HERE YOU CAN FILTER FOR ANY FILTERS...
{
$match: { "device._id" : "5d44256d8b3cf92af46e2c9b"}
},
// TRANSFORMING EVERY ELEMENT OF THE ARRAY 'device' AS A SINGLE ROW/DOCUMENT...
// EXAMPLE:
// {id: 123, "someArray":["A","B","C"]}
// --> unwind : 'someArray'
// --> [{"id": 123, "someArray": "A"},{"id": 123, "someArray": "B"},{"id": 123, "someArray": "C"}]
{
$unwind: '$device'
},
// FILTERING THE DEVICES THAT HAVE THE 'DeviceJson' PROPOERTY...
{
$match: { "device.DeviceJson" : {$exists: true}}
},
// TRANSFORMING EVERY ELEMENT OF THE ARRAY 'DeviceJson' AS A SINGLE ROW/DOCUMENT...
{
$unwind: '$device.DeviceJson'
},
// FILTERING THE ELEMENTS IN "DeviceJson"...
{
$match: { "device.DeviceJson.complexObject._id" : "5db85e439a17899b8ba631cf"}
},
// CREATING A FIELD TO STORE THE RESULT...
{
$addFields: {"DeviceJson" : "$device.DeviceJson" }
},
// SHOWING ONLY THE FIELD 'DeviceJson' IN THE RESULT...
{
$project: {"DeviceJson" : 1}
}
]);
03) Response:
{
"_id" : "5d42d171e7ceef2a90245470",
"DeviceJson" : {
"_id" : "5dae22702486f7d89ba7633c",
"name" : "deviceJsonTwo",
"complexObject" : {
"_id" : "5db85e439a17899b8ba631cf"
},
"someArray" : [
{
"someThing" : 3
},
{
"someThing" : 2
}
]
}
}

Push data in nested arrays nodeJs, MongoDB

I Have Document Like,
{
"_id" : ObjectId("5ab4cc12c773133bae3d8dc9"),
"__v" : 19.0,
"geoGraphicalFilter" : {
"aCountries" : [
{
"country" : "Spain",
"_id" : ObjectId("5ad49ab21210c42aa6ccba23"),
"cities" : [ ]
},
{
"country" : "India",
"_id" : ObjectId("5ad49ab21210c42aa6ccba24"),
"cities" : [ ]
}
]
}
}
Model
const HuntingWindow = new Schema({
geoGraphicalFilter: {
aCountries: [
{
country: String,
cities: { type: Array }
}
]
},
});
Snippet
const addCityFilter = (req, res) => {
if (req.body.aCities === "") {
res.status(409).jsonp({ message: adminMessages.err_fill_val_properly });
return false;
} else {
var Cities = req.body.aCities.split(",");
huntingModel.update({ _id: req.body.id,"data.geoGraphicalFilter.aCountries":req.body.sName },
{$push:{"geoGraphicalFilter.0.aCountries.$.cities":Cities}},
(error, data) => {
// Cities.forEach(element => {
// data.geoGraphicalFilter.aCountries.find(req.body.sName)
// });
data.save((error, success) => {
res.status(200).jsonp({
message: adminMessages.succ_countryFilter_added
});
});
});
}
};
Now I want to first Find Document by root id and then I want to match the country name and insert the cities in the Array. I am new to MongoDB and nodejs how can i do this ? While i am trying to with update query but i thing i am doing it on wrong way plese help me with it.
Try following code:
huntingModel.update(
{ _id: ObjectId("5ab4cc12c773133bae3d8dc9"), "geoGraphicalFilter.aCountries.country": "Spain" },
{ $addToSet: { "geoGraphicalFilter.aCountries.$.cities": { $each: [ "city1", "city2" ] } } }
)
You should specify two filtering conditions: one for entire document and one to match array element. Then you can use $ operator to update first matching document in that array. To push multiple values you can use $each operator. To ensure that there will be no duplicates you should use $addToSet

filter the records using loadash angularjs

var arr = Array [ Object, Object ]
into arr {
"name" : "xyz",
"age" : "22",
"sports" : Array[
{
id:1,
name : "xyz",
},
{
id:2,
name : "yyy",
},
]
}
var obj = Object { name: "JXZ", id :1};
var response = _.filter(arr, function(user) {
return user.sports.id === obj.id;
});
filter the record that match with obj's id from arr's sports.id return array object.
I'm suppose to put loop but i guess that not right solution if please
Please try this below code.
<script>
var app = angular.module('app',[]);
app.controller('ctrl',function($scope){
$scope.arr = Array [ Object, Object ];
$scope.arr = {
"name" : "xyz",
"age" : "22",
"sports" : [
{
id:1,
name : "xyz",
},
{
id:2,
name : "yyy",
}
]
}
var obj = { name: "JXZ", id :1};
var filteredSports = _.filter($scope.arr.sports, function (sport) {
return sport.id == obj.id;
})
$scope.arr.sports = filteredSports;
console.log($scope.arr);
})
</script>

MEAN-Stack MongoDB Sub Array Delete - Works in IDE, not in API

I have a [user] document stored that contains a nested sub-array [profiles],[favorites]. I am simply trying to delete($pull) a favorites from a given profile based on the favorites name.
{
"_id" : ObjectId("558d53eebdd9804820090fa1"),
"name" : "Frank",
"email" : "Frank#FrankTheTank.com",
"profiles" : [
{
"avatar" : "div-male",
"age" : "35",
"gender" : "Male",
"profilename" : "Oly Lifter",
"_id" : ObjectId("558d5404bdd9804820090fa2"),
"favorites" : [
{
"name" : "Power Clean"
},
{
"name" : "Hang Clean"
},
{
"name" : "Clean and Jerk"
}
],
"createdAt" : ISODate("2015-06-26T13:30:44.661Z")
}
],
"createdAt" : ISODate("2015-06-26T13:30:22.884Z"),
"role" : "user",
"__v" : 0
}
Using a MongoDB IDE robomongo, I'm able to successfully remove a favorite item from a known User and Profile ID using this
db.users.update($find: {
'profiles': {
'profiles._id': ObjectId("558d5404bdd9804820090fa2")
},
{
$pull: {
'profiles.$.favorites': {
'name': 'Hang Clean'
}
}
})
However, when I call from my server API using the following syntax, I receive an error, note req.body._id = "558d5404bdd9804820090fa2" and req.body.favorites.name = "Hang Clean"
User.findByIdAndUpdate(_user._id, {
'profiles._id': req.body._id
}, {
$pull: {
'profiles.$.favorites': {
'name': req.body.favorites.name
}
}
}, {
safe: true,
upsert: true
},
function(err, model) {
if (err) {
console.log(err);
return res.status(500).send('Error Deleting Profile');
}
return res.status(200).send('Profile Deleted!');
});
Try updating using the findOneAndUpdate() method since you are supplying the findByIdAndUpdate() method with the wrong parameters: the second argument { 'profiles._id': req.body._id } should be part of the first query object hence you need to use the findOneAndUpdate() method as follows, making sure you convert the string ids into ObjectId's:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId(_user._id),
profileId = mongoose.Types.ObjectId(req.body._id),
query = {
"_id": id,
"profiles._id": profileId
},
update = {
"$pull": {
"profiles.$.favorites": { "name": req.body.favorites.name }
}
},
options = { "multi": true, "upsert": true };
User.findOneAndUpdate(query, update, options, function(err, model) {
if(err){
console.log(err);
return res.status(500).send('Error Deleting Profile');
}
return res.status(200).send('Profile Deleted!');
});

Nested models in Backbone

I am new to Backbone and I have an issue regarding nested models. Here I have data.json where I have following JSON:
[
{
"name": "Project",
"description" : "This is a Peugeot website",
"url" : "http://peugeot.am",
"images" : [
{ "image" : "A", "thumb" : "a" },
{ "image" : "B", "thumb" : "b" },
{ "image" : "C", "thumb" : "c" }
]
},
{
"name" : "Ararat",
"description" : "This is a Ararat website",
"url" : "http://ararat.am",
"images" : [
{ "image" : "A", "thumb" : "a" },
{ "image" : "B", "thumb" : "b" },
{ "image" : "C", "thumb" : "c" }
]
},
{
"name" : "Procredit Bank",
"description" : "This is a Procredit Bank website",
"url" : "http://procredit.am",
"images" : [
{ "image" : "A", "thumb" : "a" },
{ "image" : "B", "thumb" : "b" },
{ "image" : "C", "thumb" : "c" }
]
}
]
In Backbone I am trying to fetch data, but I get empty array.
var myapp = myapp || {};
$(function () {
myapp.Image= Backbone.Model.extend({
initialize: function () {
this.Img = this.get('image');
this.Thumb = this.get('thumb');
}
});
myapp.Images= Backbone.Collection.extend({ model: myapp.Image });
myapp.Item= Backbone.Model.extend({
initialize: function () {
this.Name = this.get('name');
this.Description = this.get('description');
this.URL = this.get('url');
this.subs = new myapp.Images(this.get('images'));
}
});
myapp.Items= Backbone.Collection.extend({
model: myapp.Item,
url: 'content/js/data.json',
parse: function (resp, xhr) { return JSON.parse(resp); }
});
var items = new myapp.Items();
items.fetch();
console.log(items.toJSON());
});
Now, what am I doing wrong above? I need to fetch data to get JSON so to start manipulate with it.
Thanks in advance!
the default support is pretty lacking you would need to get the data for each nested model separately
There are library such as
https://github.com/powmedia/backbone-deep-model
and
http://afeld.github.io/backbone-nested/
Which can be used instead
items.fetch();
console.log(items.toJSON());
Collection.fetch() is an asynchronous operation. It won't produce a response until the request gets back from the server. Try this:
items.fetch().done(function(){
console.log(items.toJSON());
});
You can also use the web inspector in safari/chrome (or firefox debugger / firebug) to monitor network requests and see that your calls are firing successfully (and inspect the responses), or put another console.log statement inside the 'parse' function of your collection.
http://backbonejs.org/#Collection-fetch

Resources