Dynamic $in operator based on a variable - javascript

I have a variable and based on that value I would like to change the $in operator within mongo query.
My code -
var query_op = "$in";
if (criteria.group === "abc")
{
var query_op = "$nin";
}
And then
var query = Model.find(
{
_id:
{
$in: query_op
}
,
...........................
});
Would it be possible to use in this way?
Any help is highly appreciated.

I think in JavaScript you can dynamically define object's key using square brackets, try:
var query_op = "$in";
if (criteria.group === "abc")
{
var query_op = "$nin";
}
var query = Model.find(
{
_id:
{
[query_op]: listOfIds
}
});

Related

split last two words and filter in javascript

I would like to know how to filter array of values using javascript
How to seperate the arrays with 'provider-send' and 'provider-receive'
var filterradio = id.filter(function(e){
return e.id.split("-")[0] == "provider-send"
})
var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]
Expected Output:
result_sn: ["provider-send-credit-transfer", "provider-send-debit-fund"]
result_rcn:["provider-receive-credit-transfer","provider-receive-debit-fund"]
If it's always going to be "provider-receive-..." and "provider-send..." then you can do the following to separate them
for (i = 0; i < id.length; i++) {
if (id[i].split("provider-send-").length > 1) {
result_sn.push(id[i]);
} else if (id[i].split("provider-receive-").length > 1) {
result_rcn.push(id[i])
}
}
Try This :
var id = [ "provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund" ] ;
var result_sn = [] , result_rcn = [] ;
for( value of id ) {
var twoWords = value.split('-',2).join('-') ;
if ( twoWords === "provider-send" )
result_sn.push( value ) ;
else if ( twoWords === "provider-receive" )
result_rcn.push( value ) ;
}
console.log( result_sn ) ;
console.log( result_rcn ) ;
Pass 2 as second parameter to split() and then again join() by -. The second parameter to split() specifies the max number of elements in the result array.
var id=["provider-send-credit-transfer", "provider-send-debit-fund","provider-receive-credit-transfer","provider-receive-debit-fund"]
var filterradio = id.filter(function(id){
return id.split("-",2).join('-') === "provider-send"
})
console.log(filterradio)
Using .filter() will require you to write 1 filter for every pattern you want to match have assigned to a variable.
Using .reduce() is recommended and is more easily expandable to support more patterns.
It may look intimidating at first but you're essentially using accumulator as the temporary variable that gets stored and brought forward to each iteration. And each iteration of the array will give you the current iterated value with currentValue.
I've added something-else as an example of adding new pattern.
var id = [
"provider-send-credit-transfer",
"provider-send-debit-fund",
"provider-receive-credit-transfer",
"provider-receive-debit-fund",
"something-else-credit-transfer",
"something-else-debit-fund"
];
const {
'provider-send': result_sn,
'provider-receive': result_rcn,
'something-else': result_ste
} = id.reduce(function(accumulator, currentValue) {
let prefix = currentValue.match(/^\w+-\w+/)[0];
return {...accumulator, [prefix]: (accumulator[prefix] || []).concat(currentValue)}
}, {});
console.log(result_sn);
console.log(result_rcn);
console.log(result_ste);
I suggest using reduce instead of the filter as reduce is used to reduce the array size into a single returned element.
Here I am reducing the array into an object which has two keys result_sn and result_rcn.
var id = ["provider-send-credit-transfer", "provider-send-debit-fund", "provider-receive-credit-transfer", "provider-receive-debit-fund"]
const result = id.reduce((obj, str) => {
if (str.match(/^provider-send/g))
obj['result_sn'].push(str);
else
obj['result_rcn'].push(str);
return obj;
}, {
'result_sn': [],
'result_rcn': []
});
console.log(result)

fetch the array having specific value

I have the json array value which have age and number.I want to create a new set of array which has {"num":2} in it (ie)need to return [{"age":2,"num":2},{"age":3,"num":2}]
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val = {"num":1};
}
array_val.filter(fetchList)
console.log(array_val);
I see 2 issues in your code:
You don't parse your string to JSON
You have a wrong filter
function
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val.num === 2; // return only records whose num is 2
}
// here you parse string into JSON and apply the filter
var data = JSON.parse(array_val).filter(fetchList);
console.log(data);
You need to use filter()
var fetched_object = array_val.filter(function(obj) {
return obj.num == 1;
});
Note: Like #NinaScholz said you need to JSON.parse the string so it is an array.
You need parse the JSON string JSON.parse() .And matching condition was wrong .num is the inner propery of the object .so you need to match a.num == 2 .Don't forget to add ==
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(a) {
return a.num == 2;
}
var res = JSON.parse(array_val).filter(fetchList)
console.log(res);
This should do it
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
console.log(array_val);
function fetchList(array_val) {
return array_val.num == 2;
}
array_val = array_val.filter(fetchList)
console.log(array_val);
This would work instead:
var requiredValue = array_val.filter(function(item) { return item.num === 2;
});
try this
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
var newarr =[]
for(let i of array_val){
if(i.num == 2){
newarr.push(i);
}
}
console.log(newarr);

Implementing wildcard at end of a string

I looked through a number of posts (and other websites) and I seem to have a hit a roadblock. I have the following array:
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"]
I'm trying to return data for everything that has youtube.com*. Below is the relevant snippet of my function:
var result = []
for (var i=0; i<data_dictionary.length; i++) {
if (data_dictionary[i].page == /^youtube.com/) {
result.push (data_dictionary[i].page,data_dictionary[i].share)
}
}
break;
}
return result
The problematic area is in the if clause (/^youtube.com/). How can I receive the following return:
["youtube.com" , "youtube.com/feed/subscriptions"]
You can use Array.prototype.filter() method to filter array and RegExp.prototype.test() to check for match.
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"];
function check(data_dictionary) {
return data_dictionary.filter(function(v) {
return /^youtube\.com/.test(v);
// using indexOf
// v.indexOf('youtube.com') == 0;
});
}
console.log(check(data_dictionary));
FYI: Your if condition will be only true if the string is '/^youtube.com/'. ie, ('/^youtube.com/' == /^youtube.com/) === true. Your code will work if you changed the if condition to /^youtube.com/.test(data_dictionary[i]). Also in the provided data page and share properties are undefined only plain strings are the element.
Using the same approach that you had before. However using ".filter" won't be a bad idea, but I will suggest you compare their benchmark
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"];
var pattern = /^youtube.com/;
var result = [];
var i = 0;
function loop (args) {
for (i; i < args.length; i++) {
if (pattern.test(args[i])) {
result.push(args[i]);
}
}
return result;
}
console.log(loop(data_dictionary)) // ["youtube.com" , "youtube.com/feed/subscriptions"]
Comparing the speed below I would suggest you use the approach above
No need for regex here you can do like this;
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"],
filtered = data_dictionary.filter(e => !!~e.indexOf("youtube.com") && e);
document.write("<pre>" + JSON.stringify(filtered) + "</pre>");
Or if you want a faster solution still with Array methods then
var data_dictionary = ["youtube.com", "facebook.com", "youtube.com/feed/subscriptions", "twitter.com"],
filtered = data_dictionary.reduce((p,c) => !!~c.indexOf("youtube.com") ? p.concat(c):p,[]);
document.write("<pre>" + JSON.stringify(filtered) + "</pre>");

Javascript - How to filter an array of Objects by a Parameter

I have a variable which is an array of comments.
$scope.numOfCommentsCoupon
What i would like to have is a variable which is a count of the Comments inside the array that have a "couponId" of a certain value.
Here is the Comment Model
var CommentSchema = new Schema({
created: {
type: Date,
default: Date.now
},
couponId: {
type: String,
trim: true
}
});
So i need to filter it and then count it but im not sure how to.
If you have an array of comments, to do that, you could do something like this
var count = 0;
comments.filter(function(comment,index,array){
if (comment.couponId === "some_value") {
count++;
}
});
Or you could just iterate over it using the for loop. Pretty straightforward stuff to implement
I think I follow what you're trying to do and you can use array.filter
It would look like this:
var currentCouponId = 1;
var matching = yourArray.filter(function (element) { return element.couponId == 1; });
console.log(matching.length);
Youd could use reduce method on the array to get the count of coupons whose couponId is equals to a given string:
var comments = [
{
couponId : "1"
},
{
couponId : "2"
}
];
var couponIdToCount = "2";
var count = comments.reduce(function(previous, current) {
return current.couponId == couponIdToCount ? previous + 1: previous;
}, 0);
console.log(count)

Looking inside an object for a specific string using JavaScript

On JavaScript, I have the following JSON:
var mJSON = {
"monster":[
{"id":"150","name":"Richard"},
{"id":"100","name":"Gregory"},
{"id":"200","name":"Rachel"},
{"id":"250","name":"Mike"}
]
}
I need to refine this object by a string inputted by the user. For example: "100".
The result should be a new JSON like this:
var zJSON = {
"monster":[
{"id":"100","name":"Gregory"}
]
}
I tried looking in Google on easy ways to run through a JavaScript object searching for a string, but without success. There's nothing like jQuery's $.inArray too, as far I know. Anyone has any idea?
I'm thinking about converting this JSON into a string, grep it for the value inputted by the user, and then converting the string to JSON again, but I think this will be too troublesome for something that could be easy to achieve.
How about using $.map?
var id = 100;
var result = $.map(monsters, function(monster){
return monster.id == id ? monster : null;
});
JQuery.map() applies function to each argument of the array (monsters) and produces the new array that contains the values returned by the function. What is important in this case is that if function returns null then the element is removed from the resulting array.
EDIT:
As #Jan has kindly suggested in his comment $.grep suits even better! Here is the code example for your monsters:
var id = 100;
var result = $.grep(monsters, function(monster){
return monster.id == id;
});
Why don't you just loop through the array removing stuff that doesn't match?
Without using libraries, you could do something like this:
var mJSON = {
"monster":[
{"id":"150","name":"Richard"},
{"id":"100","name":"Gregory"},
{"id":"200","name":"Rachel"},
{"id":"250","name":"Mike"}
]
};
var searchTerm = "100";
var result = mJSON.monster.filter(function(e){
// if you want loose(r) searches, you could use a regex here
// rather than explicit equality
if(e.id == searchTerm)
{
return true;
}
});
console.log(result);
http://jsfiddle.net/dbrecht/MZQzM/
Use the grep method. Example:
var obj = {
monster: [
{ id: "150", name: "Richard" },
{ id: "100", name: "Gregory" },
{ id: "200", name: "Rachel" },
{ id: "250", name: "Mike" }
]
};
var input = "100";
var filtered = {
monster: $.grep(obj.monster, function(e){
return e.id == input;
})
};
var mJSON = {
"monster":[
{"id":"150","name":"Richard"},
{"id":"100","name":"Gregory"},
{"id":"200","name":"Rachel"},
{"id":"250","name":"Mike"}
]
};
var searhKey = "100";
var found = false, i = 0, pos = -1, l = MJSON.monster.length;
while(!found && i < l) {
if(MJSON.monster[i].id == searchKey) {
pos = i;
found = true;
}
i += 1;
}
if(found) {
alert(pos);
} else {
alert("not found");
}

Categories

Resources