Looking inside an object for a specific string using JavaScript - 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");
}

Related

Dynamic $in operator based on a variable

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
}
});

How to loop through all the array of objects?

I have an Array of Object to be used to draw a HTML Table:
Array(5)
0: Object
id: 4
name: Sand Jane
address: Green Sand Street
...
...
...
1: Object
2: Object
...
...
...
I am able to do a single name column defined search with
const temp = this.temp.filter(function (d) {
return d.name.toLowerCase().indexOf(val) !== -1 || !val;
});
temp will contain the filtered data of this.temp
Now I just can't figure out how to loop through all object keys (id,name,address...) so that I can do a global column search in the Table.
UPDATE: I have tried this,
const temp = [];
this.temp.forEach(element => {
for (let key in element) {
if (element.hasOwnProperty(key)) {
let v = element[key];
if (v.toString().toLowerCase().indexOf(val) !== -1 || !val) {
temp.push(element);
}
}
}
});
It works but with performance issues.
RESOLVED: Putting a break after temp.push fixed this issue. Thank you all for the guidelines and references.
temp.forEach(item=>{
for(let key in item) {
//item[key] gives you access to each value
}
})
You can iterate through for loops or even you can usefor loop inside a for loop. Either way it's self explanatory.
var dictionary = {
"employee1":[
{"id":"0","name":"Google"},
{"id":"1","name":"eBay"}
],
"employee2": [
{"id":"2","name":"Yahoo"},
{"id":"3","name":"Facebook"}
]
};
var employee1 = dictionary.employee1;
var employee2 = dictionary.employee2;
for ( var i in employee1) {
var id = employee1[i].id;
var name = employee1[i].name;
console.log(id);
console.log(name);
}
for ( var i in employee2) {
var id = employee2[i].id;
var name = employee2[i].name;
console.log(id);
console.log(name);
}

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)

Get value from json object without count the array number

This is my json object i want to get alert it without the array order like[0], [1].
var jsononj = {
"objnew" :
[{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
] };
}
var newtest = jsononj.objnew[0].testarry;
alert(newtest);
i want to alert without [0]. how to i achieve this
I think this is what you're looking for:
var i;
for (i = 0; i < jsonobj.objnew.length; i++) {
if (jsonobj.objnew[i].testarry) {
alert(jsonobj.objnew[i].testarry);
}
}
This is just stupid but I removed the [0]
var jsononj = {
"objnew" : [
{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
]
};
var a = jsononj.objnew.shift();
alert(a.testarry);
jsononj.objnew.unshift(a);
That's not JSON, that's a Javascript object. JSON is a text format for representing data.
If you want to look for an object with a specific property, loop through the objects in the array and check for it:
var newtest = null;
for (var i = 0; i < jsononj.objnew.length; i++) {
var obj = jsononj.objnew[i];
if (obj.hasOwnProperty('testarry') {
newtest = obj.testarry;
break;
}
}
if (newtest != null) {
// found one
}
doing a var firstOne = jsononj.objnew[0];
but if you simply don't like the [0] through your lines, extend the Array prototype
Array.prototype.first = function () {
return this[0];
};
var newtest = jsononj.objnew.first().testarry;
alert(newtest);
more info at First element in array - jQuery

Categories

Resources