Mysql Like statement in javascript with array of objects? - javascript

I am pretty confused with relative searching in javascript For example
let array = [{name:'ram'},{name:'kumar ra'},{name:'nani'}]
If i search ra then array should be like [{name:'ram'},{name:'kumar ra'}]Similar to mysql Like statement .But i don't know how to do it in javascript ..
Thanks in advance..

Arrays have a filter (Array.prototype.filter) method which behaves very much like a where clause.
It takes a predicate and returns a new array containing the elements that satisfy that predicate.
const array = [{
name: 'ram'
}, {
name: 'kumar ra'
}, {
name: 'nani'
}];
const filtered = array.filter(e => e.name.match(/ra/));
console.log(filtered);
In the predicate itself, we use String's match (String.prototype.match) method to test each name against a regular expression. This is conceptually similar to a like expression in SQL.
The filter method walks the array and calls the predicate on each element of it. I have named this element e in inside the predicate. When the filter method calls the predicate, it passes the current element as the first argument thus binding it to e.

you can apply filter method on array elements to find items that their names contains 'ra'
let result=array.filter((item)=>{return item.name.contains('ra')})

Related

Validate if object has string

I have this array
switched = {"Restaurant":1,"Hotel":2,"Beauty shop":3,"Physiotherapist":4,"Dentist":5,"Bar":6,"Coffee shop":7}
and this object
result = [{"Google Place URL":"http://www.restaurant.com","Business Type":"Restaurant"},{"Google Place URL":"http://www.hotel.com","Business Type":"Hotel"}]
I want to validate if every item of the result contains words of switched
also, I'm already working with a for that returns each item separately
item[csvBusinessType] = Restaurant
how can I validate if item[csvBusinessType] is included in switched?
I have tried with
let n = switched.includes(item[csvBusinessType]);
but I get Uncaught TypeError: switched.includes is not a function
There is not good native method for this. Better to use lodash library https://www.npmjs.com/package/lodash
Here is an example
const _ = require('lodash');
console.log( _.includes(switched, item[csvBusinessType]));
I converted the object to string and used includes, I don't know if it will be the best way, but I think it is the most supported by browsers
let businessListArray = JSON.stringify(switched);
let checkBusiness = businessListArray.includes(item[csvBusinessType]);
I want to validate if every item of the result contains words of switched
If you want to validate that every item of the result object array contains words of the switched array, you should look into JS Array methods and working with Objects, just as #Andreas suggested.
In this specific case, your switched object has keys that appear to match the csvBusinessType of your item objects. This is helpful as we can use Object.keys() to grab all the keys of your switched object as an array of strings.
const businessTypes = Object.keys(switched) // = ["Restaurant","Hotel","Beauty shop","Physiotherapist","Dentist","Bar","Coffee shop"]
Now that we have grabbed the keys that you want to check against, we can use the JS Array method every() to perform a test against every object in your result object array. In this case, we will be testing that the obect's Business Type is included in our newly created businessTypes array.
const resultsValid = result.every((resultObject) => businessTypes.includes(resultObject["Business Type"]));
resultsValid is a boolean that is true if all objects in result had a Business type that matched one of the keys of your switched object.
NOTE: You may want to check Letter Casing before some of these comparisons unless you want to explicitly match only exact matches ("Beauty shop" will NOT match "Beauty Shop" for example).

How do I see if a character exists within each instance of the array as I type within an array of objects?

I've been struggling with this issue so I thought I'd come here to find the fix. I'm trying to filter my objects that are in an array to only show the ones that have for example "h" in them.
This is how my array of objects is being constructed:
Object.keys(data.jello).forEach(function (id, SomeSearchValue) {
var jello = data.jello[id];
array.push({
id: jello.id,
name: jello.name,
type: 'foo',
});
}
For example, let's say my array consists of this for names.
array[blue, red, green, apple, abigail, alien]
So, I have an array of objects. In a search bar I type "a" and my array results are then all objects that have a letter 'a' in the name. so...
array[abigail, alien]
Then i type a "b" so my search is now "ab" and my array is ...
array[abigail]
So what would my code to implement this using jQuery?
The part I'm stuck on most is the actual searching as the user types without using ajax.
I'm using jQuery. Ive tried things like jQuery.grep(), inArray() but cant seem to search includes. I've also tried array.includes(). Thanks for the help!
Use Array#filter().
jQuery $.grep() is basically the same thing but also works on jQuery objects.
Following assumes you only want to search within name property and will accept the term found in any part of the name rather than just at beginning
const data = [{name:'blue'}, {name:'red'}, {name:'green'}, {name:'apple'}, {name:'abigail'}, {name:'alien'}];
const term ='ab';
const filtered = data.filter(({name}) => name.toLowerCase().includes(term.toLowerCase()))
// or use startsWith() to only match beginning of string
console.log(filtered)

check if an array "includes" an item in Javascript [duplicate]

This question already has answers here:
Javascript: Using `.includes` to find if an array of objects contains a specific object
(7 answers)
Closed 28 days ago.
I am trying to understand the array "includes" function. My goal is to determine if an array includes a certain item. It works fine for an array of strings but when using objects it doesn't work.
var itemsString = ["name1", "name2"];
var itemsObject = [{ name: "name1" }, { name: "name2" }];
var itemToSearch = { name: "name1" };
console.log(itemsString.includes("name1" ));
console.log(itemsObject.includes(itemToSearch));
console.log(itemsObject.includes(x => x.name === "name1"));
Output:
true
false
false
Does "includes" work with objects or do I need to use another function?
You need to use Array.prototype.some() in this case. Array.prototype.includes() does not accept a function parameter*, and you're not testing for strict equality.
const itemsObject = [{ name: "name1" }, { name: "name2" }];
console.log(itemsObject.some(x => x.name === "name1"));
*Peer pressure from the comments section forces me to clarify that includes() does accept function parameters, but will not use the passed function as a predicate to determine whether a given item matches. Rather, it will try to find an item in the array that is strictly equal to the passed function.
In your last line you check wether a function is inside of your array. .includes also works for objects, but it compares them by reference. In your case you probably want to .find or check wether .some of the objects match your query.
Does "includes" work with objects or do I need to use another
function?
Includes works with objects, but it compares objects by reference.
In your case, despite the first element of itemsObject has the same keys and values of itemToSearch, they are different objects, hence includes will not work, since, for objects cases, it looks for the same object instance.
In order to make it work, you can use several alternatives, like .find, .some, .filter.
Another solution, which I personally don't recommend but I think that it's worth mentioning, is that you can use .includes if you first map items to strings instead. In that case, using JSON.stringify, you can check whether the objects are the same. BEWARE: this will work with single key items only. JSON.stringify doesn't preserve key and values order, so it works with single keys objects only (unless keys and values are in the same order in the original stringified object). Moreover, the JSON.stringify way is way heavier and less performant than the others, I just think it's worth mentioning that as an example.
Below some examples with each of them.
var itemsString = ["name1", "name2"];
var itemsObject = [{ name: "name1" }, { name: "name2" }];
var itemToSearch = { name: "name1" };
console.log(itemsObject.some(r => r.name === itemToSearch.name));
console.log(!!itemsObject.find(r => r.name === itemToSearch.name));
// ^--- !! is used to cast to boolean.
console.log(itemsObject.filter(r => r.name === itemToSearch.name).length > 0);
console.log(itemsObject.map(i => JSON.stringify(i)).includes(JSON.stringify(itemToSearch)));
// ^--------------^ ^---------------------------------------^
// |------ this will stringify each object, converting it to a json string. |
// |
// this will check whether the string[] includes any stringified value.--^

Find if already exists, JS and Lodash

So I have an interesting issue I am not sure how to follow, I need to use lodash to search two arrays in an object, looking to see if x already exists, lets look at a console out put:
There are two keys I am interested in: questChains and singleQuests, I want to write two seperate functions using lodash to say: find me id x in the array of objects where questChains questChainID is equal to x.
The second function would say: Find me a quest in the array of objects where singleQuests questTitle equals y
So if we give an example, you can see that questChainId is a 1 so if I pass in a 1 to said function I would get true back, I don't actually care about the object its self, else I would get false.
The same goes for singleQuests, If I pass in hello (case insensitive) I would get back true because there is a quest with the questTitle of 'Hello'. Again I don't care about the object coming back.
The way I would write this is something like:
_.find(theArray, function(questObject){
_.find(questObject.questChains, function(questChain){
if (questChain.questChainId === 1) {
return true;
}
});
});
This is just for the quest chain id comparison. This seems super messy, why? Because I am nesting lodash find, I am also nesting if. It gets a bit difficult to read.
Is this the only way to do this? or is there a better way?
Yeah it can be expressed more simply.
Try something like this:
var exampleArray = [{
questChains: [{
questChainId: 1,
name: 'foo'
}, {
questChainId: 2,
name: 'bar'
}],
singleQuests: [{
questTitle: 'hello world'
}]
}, {
questChains: [{
questChainId: 77,
name: 'kappa'
}]
}];
var result = _.chain(exampleArray)
.pluck('questChains')
.flatten()
.findWhere({ questChainId: 2 })
.value();
console.log('result', result);
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>
Using chain and value is optional. They just let you chain together multiple lodash methods more succinctly.
pluck grabs a property from each object in an array and returns a new array of those properties.
flatten takes a nested array structure and flattens it into flat array structure.
findWhere will return the first element which matches the property name/value provided.
Combining all of these results in us fetching all questChain arrays from exampleArray, flattening them into a single array which can be more easily iterated upon, and then performing a search for the desired value.
Case-insensitive matching will be slightly more challenging. You'd either need to either replace findWhere with a method which accepts a matching function (i.e. find) or sanitize your input ahead of time. Either way you're going to need to call toLower, toUpper, or some variant on your names to standardize your search.

Nodejs: How to search for a substring within an array in javascript?

Assuming that I have an array that looks like the one below:
["file1.java", "file32.js", "file44.java", "file4.html", "file15.js"]
I would like to filter out only the elements that end in ".java". Therefore I would like to somehow be able to search for the substring ".java" as I'm iterating through each element in my array. How do I go about doing this? Thank you
You can use the filter() method of the Array type:
var files = ["file1.java", "file32.js", "file44.java", "file4.html", "file15.js"];
var filtered = files.filter(function(item) {
return item.endsWith(".java");
}
);
console.log(filtered);

Categories

Resources