How to find text inside an array from a json file? - arrays

I have a json array called "names". I want to prevent repeating the same name by searching it before it is entered on the array.
I find this code, but i need also to run the function enterName if the name is not repeated.
Thnaks
var name = "TEST";
for (var i = 0; i < config.names.length; i++){
if (config.names[i] == name){
console.log("name repeated");
}
}

Try this
if (!config.names.find(p=>p===name))
enterName(name);

Using ES7
const name = "TEST";
if (!config.names.includes(name)) {
enterName(name);
}

Related

Meteor compare elements in array

I'm just beginning the adventure of a meteor, so I have a little problem
The database structure looks like this:
users have roles, the roles have subroles. I want to check whether the user has at least one of the subrole, which is a function argument as an array.
Here's the code:
userHasAllPermissions: function(permissionArray) {
var result = false;
var user = Meteor.user();
if (!user) return false;
permissionArray = ["Permission 0", "Permission 1", "Permission 99999"];
var rolesToSearch = _.keys(user.roles);
for (var i = 0; i < rolesToSearch.length; i++) {
var role = Meteor.roles.findOne({name: rolesToSearch[i]});
var subrole = role.subRoles;
for(var k = 0; k < permissionArray.length; k++)
{
if(_.include(_.some(subrole,permissionArray[k]))){
result = true;
console.log("Ok");
break;
}
console.log("Error")
}
}
return result;
}
OK, right off the bat:
On line 5, you seem to be overwriting your permissionArray function argument. Are you sure you want to do that?
Is user.roles an Object or an Array? I'd expect an array, but then _.keys(user.roles) doesn't make sense.
It would be way more efficient to use the $in mongo query to get the subroles, you can then iterate over the resulting cursor. In fact, perhaps you can use two $in query operators to get your result right away: Meteor.roles.find({name:{$in:rolesToSearch}, 'subRoles.$':{$in: permissionArray}}) It's hard to test this, but I'm guessing you can find a query like that - if it returns a result - should let your function return true.
user.roles is Ocject, user.roles have Array of subRoles

Removing records that exist in an array from ExtJS store

I have a store and an array. I want to remove records from the store if that record's value matches with values in the array. Following is is the code I am trying but it's not working. Can anyone suggest the correct way?
'store' is the actual store and 'filterItems' is the array of records I want to remove from 'store'.
store.each(function (record) {
for (var i = 0; i < filterItems.length; i++) {
if (record.get('ItemId') === _filterItems[i].get('ItemId')) {
itemIndex = store.data.indexOf(record);
store.removeAt(itemIndex );
}
}
});
Not sure about your code because i dont know all variables. Though its recommended to use the store.getRange() fn and iterate the array via for loop. Its better for performance.
var storeItems = store.getRange(),
i = 0;
for(; i<storeItems.length; i++){
if(Ext.Array.contains(filterItemIds, storeItems[i].get('id')))
store.remove(store.getById(storeItems[i].get('id')));
}
Here is an example which i tried right now and it works well.
https://fiddle.sencha.com/#fiddle/8r2
Try using the remove method of the store (docs)
store.remove(filterItems);
var indexes = [], i = 0;
dataviewStore.each(function(item, index){
if(item) {
if(item.data.columnId == columnId) {
indexes[i++] = index;
}
}
}, this);
dataviewStore.remove(indexes);
this is my example if your record is matches with the value then store the index of that item after storing indexes of all the items and remove them.
Otherwise you have to use for loop and remove them from end of the array.

Arrays and if statements. How to check if value is in array? *javascript*

So I have a program that sends emails. The user has a list of emails that cannot be sent to. These are in arrays and I need to use a if statement to determine if what the user entered in is in the array of emails. I tried the in function which didnt work but Im probably just using it wrong. I tried for loops and if statements inside. But that didnt work either. Here is a snapshot of the code Im using to help you get the idea of what im trying to do.
function test2(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "lol"
Logger.log("entry: " + entry)
for(i = 0; i < safe.length; i++){
if(entry == safe[i]){
Logger.log("positive")
}else{
Logger.log("negative")
}
}
}
Here is what I tried with the in function to show you if I did it wrong
function test(){
var safe = [1]
safe[1] = "lol"
safe[2] = "yay"
var entry = "losl"
Logger.log("entry: " + entry)
if(entry in safe){
Logger.log("came positive")
}else{
Logger.log("came negative")
}
Logger.log(safe)
}
array.indexOf(element) > -1 usually does the trick for these situations!
To expand upon this:
if (array.indexOf(emailToSendTo) < 0) {
// send
}
Alternatively, check this cool thing out:
emailsToSend = emailsToSend.filter(function(x) {
// basically, this returns "yes" if it's not found in that other array.
return arrayOfBadEmails.indexOf(x) < 0;
})
What this does is it filters the list of emailsToSend, making sure that it's not a bad email. There's probably an even more elegant solution, but this is neat.

substring from an array as3 **Error #1009: Cannot access a property or method of a null object reference

I am trying to create a matching game where one object in the array hitBoxes is matched to one object in the array hitBoxes2. I have tried to convert the instance name into a string and then used the substring method to match the LAST number in the instance name, if its a match they win. Right now I'm getting the error
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at MethodInfo-499()
I'm wondering if anyone can help me. Thanks!
var left:String;
var correct:MovieClip = new Correct;
var isClicked:Boolean = false;
var leftClicked:int = 0;
p3.nextPage.buttonMode = true;
p3.nextPage.addEventListener(MouseEvent.CLICK, nextPage);
function nextPage(MouseEvent):void{
removeChild(p3);
}
var hitBoxes:Array = [p3.a1, p3.a2, p3.a3, p3.a4, p3.a5, p3.a6, p3.a7, p3.a8];
var hitBoxes2:Array = [p3.b1, p3.b2, p3.b3, p3.b4, p3.b5, p3.b6, p3.b7, p3.b8];
for (var h:int = 0; h < hitBoxes.length; h++){
hitBoxes[h].buttonMode = true;
hitBoxes[h].addEventListener(MouseEvent.CLICK, matchingLeft);
}
for (var h2:int = 0; h2 < hitBoxes2.length; h2++){
hitBoxes2[h2].buttonMode = true;
hitBoxes2[h2].addEventListener(MouseEvent.CLICK, matchingRight);
}
function matchingLeft(e:MouseEvent):void{
var left = String(e.currentTarget.name);
isClicked = true;
trace(left);
}
function matchingRight(e:MouseEvent):void{
var right:String = String(e.currentTarget.name);
trace(right);
if(isClicked == true && left.substring(3,3) == right.substring(3,3)){
trace("matched");
}
}
According to your code variable "left" is null at matchingRight method, because matchingLeft uses its local variable with name "left", and top-level "left" still has its default value.
also String.substring method is used incorrectly:
var name:String="p3.a1";
trace(name.substring(3, 3)); // this will always output empty string ""
trace(name.substring(4, 5)); // this will output "1" string
in conclusion I'd advise to use array indices (integers) instead of strings when calculating "matched" condition, substring operation and string comparison are CPU intensive.

JSON: How do I select an array inside another array?

I have the current JSON file:
[{"id":"1","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]},
[{"id":"2","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]}
How do I select the array with ID 1 and list every 'img_id' inside it, without repeating it for the other array?
edit 1:
I am trying to parse it like this but this code is erroneous:
$("#button").click(function() {
$.getJSON("../path/to/json", function(data) {
$.each(data[0].images.img_id, function(i,data){
var new_data ="<p src='path/to/folder/"+images.img_id+"'></p>";
$(new_data).appendTo("#htmlTag");
});
}); return false;
});
Much appreciated.
You have an array of objects, where each object contains another array of objects. I'm assuming the JSON structure you are using is:
var a = [{"id":"1","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]},
{"id":"2","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]}];
I'm also assuming you are using JavaScript.
PostEdit:
Your code is fairly close, I believe what I have below should work:
$("#button").click(function() {
$.getJSON("../path/to/json", function(data) {
$.each(data[0].images, function(i,data){
var new_data ="<p src='path/to/folder/" + data.img_id + "'></p>";
$(new_data).appendTo("#htmlTag");
});
});
return false;
});
All I did was change the first parameter to your each call from: data[0].images.img_id to: data[0].images. Also, I changed the declaration of new_data from:
var new_data ="<p src='path/to/folder/"+images.img_id+"'></p>";
to:
var new_data ="<p src='path/to/folder/"+data.img_id+"'></p>";
Note that the parameter "data" in the each callback function is simply the element in the array, while "i" is the index of that element in the array. Therefore, data is an object which looks like this:
{"img_id":1}
So, you can get the ID via data.img_id. Hope this helps.
I think you're talking about references. I don't think they are possible in JSON. In case you strictly need them and still want the readable serialization of your objects - I'd suggest you to look into YAML
I think there is a typo in your JSON...it seems like a bracket is missing at the end, and one has been added at the start of line 2. But, assuming you meant this (and are using Javascript):
var myJson = [{"id":"1","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]},
{"id":"2","images":[{"img_id":"1"},{"img_id":"2"},{"img_id":"3"}]}];
then you can access whatever you need just like a nested Javascript object. If you wanted to only access the object with ID equal to 1, and order is not guaranteed, you would have to iterate:
for(var i = 0; i < myJson.length; i++){
if(myJson[i].id === "1"){
var imgs = myJson[i].images;
for(var j = 0; j < imgs.length; j++){
//do what you want with imgs[j].img_id
}
}
}

Resources