Using maps over template literals - javascript

so I need to print a boolean value if the given string contains [[placeholder:var3]] but the var3 will be dynamically fed from an array as belwo:
const delmethod = ['all', 'email', 'sms', 'fax', 'voice', 'voicemail', 'pager', 'pagerTwoWay'];
let languages = organizationLocales.map(a => a.locale);
let variabless = alertDetails.variables?.map(k => k.name); languages && languages.length > 0 && languages.map(lang => { delmethod.map(i => {
if ( alertDetails.alertMessage?.[${lang}]?.[i]?.variabless?.some(el => [i] === [[placeholder:${el}]]) )
{ bodyContainsVariables = true; } }); })
I tried using map around the template literals but it is throwing me an error also tried like above eg but it checks only first value of the array, so can someone please help me solve this, I'd appreciate any help, thanks in advance.
updating the question with the actual PS. organizationLocales is an array and alertDetails is an object that has an variables array, Delmethod is an array is being used to check the different properties dynamically

[[placeholder:${variabless}]] yields [[placeholder:var1,var2,var3]]. It doesn't check the first variable. And that's not how Array.string.includes is supposed to be used. For checking exact match use the === operator.
In case you want to check if any of the array elements match the string you can use the Array.prototype.some method which returns a boolean value.
let any = variabless.some(el => s === `[[placeholder:${el}]]`)
If you want to find the element that matches with the string use the Array.prototype.find function.

You need to tell the index inside template literals becasue variabless is an array like this:
console.log(s.includes(`[[placeholder:${variabless[2]}]]`));
I hope it helps you.

To match against any value in variabless, you can test against a regular expression:
console.log(new RegExp(
`\\[\\[placeholder:(${variabless.join('|')})\\]\\]`
).test(s));

you're currently passing the whole array in
s.includes([[placeholder:${variabless}]])
and that's won't work, you need to specify which elemnt of the variables array you want to inject to your string which is element indexed with 2 so it should be like that
s.includes([[placeholder:${variabless[2]}]])

Related

react js get value from object based on key name

my return object looks like this. I would like to extract the value if code==="targetDate". Could someone please help.
Use the JavaScript array find function:
const matched = this.props.notifications.data.find(item => item.value === "targetDate");

Grab an object out of objects base on specific field value

In my AngularJS
this.device return 15 objects. Each object contain a dataType field and it has diff values on all 15 of them. I would like to grab/access only if dataType == "PROTOCOL" I would do something like this if I have access to underscore.js, but in this project, I don't have it.
this.device.protocol = _.find(this.device, {dataType: "PROTOCOL"});
What is JS way to access this without having to do a for-loop?
You can use Array#find.
The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
this.device.protocol = this.device.find(x => x.dataType === "PROTOCOL");
You can use Array.filter and check against your desired property.
this.device.protocol = this.device.filter(({dataType}) => dataType == "PROTOCOL")[0];

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).

Trying to shorten redundant Javascript code

This is a working javascript code. However, it looks redundant to me. Is there any way to clean this up?
let text = 'Some search text';
const searchMatch =
entry.title.toLowerCase().includes(text.toLowerCase()) ||
entry.description.toLowerCase().includes(text.toLowerCase()) ||
entry.keywords.toLowerCase().includes(text.toLowerCase());
return searchMatch;
You could do something like this:
const text = 'Some search text'.toLowerCase();
return [entry.title, entry.description, entry.keywords].some(s => s.toLowerCase().includes(text));
You might use an array and a .some test instead:
const textLower = text.toLowerCase();
return ['title', 'description', 'keywords']
.map(prop => entry[prop].toLowerCase())
.some(s => s.includes(textLower));
If, by chance, entry contains only those properties, then you could use Object.values instead:
return Object.values(entry)
.map(s => s.toLowerCase())
.some(s => s.includes(textLower));
You could just use a one-line return statement involving an array composed of entry.description, entry.keywords and entry.title, and then using Array.prototype.some() to return a Boolean (true/false) value depending on whether any of the tests pass:
return [entry.description, entry.keywords, entry.title].some(string => string.toLowerCase().includes('Some search text'.toLowerCase());
Here's essentially a breakdown of each part:
[entry.description, entry.keywords, entry.title].some(...)
What this does is makes an anonymous array composed of entry.description, entry.keywords, and entry.title (the order does not matter) and iterates through it with the Array.prototype.some() method. According to the MDN page, .some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function.
Essentially iterates through each element, and depending on the callback from the provided function, and provides a Boolean value (true if at least one element in the array passes the test, false if no elements pass the test).
string => string.toLowerCase().includes('Some search text'.toLowerCase())
This is the anonymous function contained within the .some() method, and it takes a single parameter string. Then it returns a Boolean value, depending on the outcome of the .includes() method. The .includes() method returns another Boolean value, depending on whether the lowercased string contains the lowercased 'Some search text'. It's a mouthful, but in a nutshell, the line of code above reads:
If string in lowercased form includes 'Some search text' in lowercased form, return true - otherwise, return false.
Hopefully this helps you!

use lodash to find substring from array of strings

I'm learning lodash. Is it possible to use lodash to find a substring in an array of strings?
var myArray = [
'I like oranges and apples',
'I hate banana and grapes',
'I find mango ok',
'another array item about fruit'
]
is it possible to confirm if the word 'oranges' is in my array?
I've tried _.includes, _.some, _.indexOf but they all failed as they look at the full string, not a substring
You can easily construct an iteratee for some() using lodash's higher-order functions. For example:
_.some(myArray, _.unary(_.partialRight(_.includes, 'orange')));
The unary() function ensures that only one argument is passed to the callback. The partialRight() function is used to apply the 'orange' value as the second argument to includes(). The first argument is supplied with each iteration of some().
However, this approach won't work if case sensitivity matters. For example, 'Orange' will return false. Here's how you can handle case sensitivity:
_.some(myArray, _.method('match', /Orange/i));
The method() function creates a function that will call the given method of the first argument passed to it. Here, we're matching against a case-insensitive regular expression.
Or, if case-sensitivity doesn't matter and you simply prefer the method() approach, this works as well for ES2015:
_.some(myArray, _.method('includes', 'orange'));
Two quick ways to do it - neither uses lodash (sorry)
var found = myArray.filter(function(el){
return el.indexOf('oranges') > -1;
}).length;
if (found) { // oranges was found }
or as I mentioned in the comment:
var found = myArray.join(',').indexOf('oranges') > -1;
if (found) { // oranges was found }
You can do this using lodash, but it's also very doable using native javascript methods:
function stringArrayContains(array, str) {
function contains(el) {
return (el.indexOf(str) !== -1) ? true : false;
}
return array.some(contains);
}
Testing the above function:
var a = ['hello', 'there'];
var b = ['see', 'ya', 'later'];
stringArrayContains(a, 'ell') // true
stringArrayContains(a, 'what') // false
stringArrayContains(b, 'later') // true
stringArrayContains(b, 'hello') // false
Array.prototype.some applies a function you define to every element of an array. This function (named contains in our case) must return true or false. While iterating through the array elements, if any of the elements returns true, the some method returns true.
Personally, I think in general that if you can use native JS methods for simple functions, it's preferable to loading an library just to do the same thing. Lodash absolutely does have performance benefits, but they aren't necessarily realized unless you're processing large amounts of data. Just my two cents.
Cheers!
The best way is to define a function to check the inclusion of a substring.
var contains = _.curry(function (substring, source) {
return source.indexOf(substring) !== -1;
});
I use _.curry here to get a curried function, which can be partially applied then.
_.some(myArray, contains('item'));
You can also find a substring in a joined string.
contains('item', _.join(myArray))
UPD:
I have not noticed that lodash already has a function to find value in a collection.
The function _.includes is quite the same to what I defined above. However, as everything in lodash, it uses the different order for arguments. In my example, I put a source as the latest argument for a curried function which makes my function useful for point-free style programming when lodash waits for the source as a first argument of the same function.
Check the Brian Lonsdorf's talk on this matter https://www.youtube.com/watch?v=m3svKOdZijA
Also take a chance to look into ramda. This library provides a better way for practical functional programming in JavaScript.
I ran into this Question / Answer thread while trying to figure out how to match a substring against each String in an Array and REMOVE any array item that contains that substring.
While the above answers put me on track, and while this doesn't specifically answer the original question, this thread DOES appear first in the google search when you are trying to figure out how to accomplish the above removal of an array item so I figured I would post an answer here.
I ended up finding a way to use Lodash's _.remove function to remove matching array strings as follows:
// The String (SubString) we want to match against array (for dropping purposes)
var searchSubString = "whatever"
// Remove all array items that contain the text "whatever"
_.remove(my_array, function(searchSubString) {
return n.indexOf(searchSubString) !== -1;
});
Basically indexOf is matching against the position of the substring within the string, if the substring is not found it will return -1, when indexOf returns a number other than -1 (the number is the SubString position in number of characters within the Array string).
Lodash removes that Array item via array mutation and the newly modified array can be accessed by the same name.
_.some(myArray, function(str){
return _.includes(str, 'orange')
})
let str1 = 'la rivière et le lapin sont dans le près';
let str2 = 'product of cooking class';
let str3 = 'another sentence to /^[analyse]/i with weird!$" chars#';
_.some(_.map(['rabbit','champs'], w => str1.includes(w)), Boolean), // false
_.some(_.map(['cook'], w => str2.includes(w)), Boolean), // true
_.some(_.map(['analyse'], w => str3.includes(w)), Boolean), // true

Categories

Resources