How to delete object from array if value matched from other object? - javascript

I have already existed array of object values now when i delete dataItem dataItem has same properties that i have in selectedOwners so if dataItem selected value matched i want to delete that object from selectedOwners array.
How can i achieve that task using AngularJs or Javascript ?
ctrl.js
var selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571}];
$scope.deleteOwner = function(dataItem){
angular.forEach(selectedOwners,function(val,index){
if(val === dataItem){
selectedOwners.splice(index,1);
}
})
}

Unfortunately in Javascript you don't have many instrument for a good equality checking, and === isn't enough, === don't force javascript to convert the two operand in order to perform the equality check on the same type of object, we let say that in this way you have true if the two objects have the same memory reference false otherwise.
For this reason you should decide the your equality criteria and wrap this login in a function. I discourage to use something like this Object.prototype.equals because in the sway you will have the same behavior for all objects in your script
the rest of code that you had post is good in my opinion but you have implements a equality checking
I hope that this can help you

Related

Loop through object containing boolean values

I have an object in key/value pairs that may contain boolean values. I need to evaluate the type of the value so I know what to return. So let's say I have an object that looks like:
{
aKey: false,
anotherKey: 4,
yetAnotherKey: true
}
I want to loop through each key/value pair there and do something different depending on the type of the value. If I use Object.keys(options).map((key, index), it transforms the boolean values from true/false to 0/1, so I have no way of knowing that those are actually booleans.
What is the best way to go about this?
I think you just "oopsied" - you haven't even checked the value of the options object in your map function. The second parameter provided to an Array#map callback is always the index.
Extending your code to check the type of the value in options:
Object.keys(options).map((key, i, all_keys) => {
let val = options[key];
console.log(typeof val)
...
});
Consider reviewing the different methods of iteration / enumeration in JavaScript, e.g.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
How to iterate over a JavaScript object?
Your .map(key, index) is looping over the array ["aKey", "anotherKey", "yetAnotherKey"] and losing the values in options. Maybe something like this would work for you:
for( o in options ){
console.log(o, options[o])
}
> aKey false
> anotherKey 4
> yetAnotherKey true

find value in complex object javascript

Basically I have a complex object that retrieves the GPT API (google publisher tag) with this function:
googletag.pubads().getSlots();
The object value is something like this:
I need to know if there is a way to compare the value of each property with an X value without getting a problem of recursivity (because the object is huge and i need to to that validation several times)
Also, I tried to convert that object into a JSON with JSON.stringify(), and then tried to get the value with a regex, faster, but with this option, I have the problem with Cyclic Object Value.
Any suggestions ?
it's more simple. try it to convert it into an array and later use a filter for comparative with your value.
var objGoogle = {};
var arrayObjectGoogle = [objGoogle];
var filter = arrayObjectGoogle.filter(function(obj){
obj.yourAttr == yourValue; });
this will give you a second array with the values found it. later, index the array for pick up the value do you need.

Safe way to check if array element exists?

I have a 2D array.
I currently access that array using notation such as:
myArray[5][9] (for example).
What is the safest way to check whether or not a certain array element exists?
For example, let's say I am looping through the array and retrieving a property of each array element like so:
myArray[5][9].firstName
I then come to myArray[9][11].firstName (for example) which doesn't exist. Clearly this will throw an exception as the element doesn't exist.
How can I deal with this? I'm not looping through the entire array (i'm accessing it's contents randomly and say using myArray.lengthin a for loop will not work.
Is there a JS function / method for checking whether or not an array element exists?
Thanks.
Safe call operator ?. looks fine. Warning: many, but not all implementations (and versions) of JavaScript supports it.
For your example it will looks like
myArray[5][9]?.firstName
EDIT: Thanks to Asaf's comment there is safer version
myArray?.[5]?.[9]?.firstName
like
if (!('firstname' in myArray[i][j])) { ... }
Just check it with if condition.
if(myArray[i][j].firstName){
}
You can use the hasOwnProperty method to check if an array item exists:
if (myArray.hasOwnProperty(x) && myArray[x].hasOwnProperty(y)) {
var name = myArray[x][y].firstName;
}
This checks both dimensions. If you know that the first index (x in the example) is always inside the range, you can skip the first test.
If you store some other values in the array also, you would need to check if the item has the firstName property:
if (myArray.hasOwnProperty(x) && myArray[x].hasOwnProperty(y) && myArray[x][y].hasOwnProperty('firstName')) {
var name = myArray[x][y].firstName;
}

Updating observable array in knockout

I have an observable array named administrators. I also have an object named adminToAdd. AdminToAdd contains a single item with the exact same properties as administrators. I'm able to push adminToAdd into administrators with no issue.
Unfortunately, I'm unable update an existing item in administrators. I'm receiving the item to update in adminToAdd. I've tried
vm.administrators.replace(vm.administrators.indexOf(vm.adminToAdd), vm.adminToAdd);
but although the structure is the same between them the index won't match. I've looked at several examples but none seem to work for my scenario. Any ideas?
The reason why your approach doesn't work is because when you use indexOf in trying to find an object rather than a value. When finding an object it uses the memory addresses to decide equality rather than the values of the object.
I love ko's utility function ko.utils.arrayFirst(array, predicate) for situations like these. This allows you to search for a specific item within an array and return it if found. You provide a predicate function that will return true in the event that the object is equal or false for anything else.
var existingItem = ko.utils.arrayFirst(vm.administrators(), function (item) {
return <true or false statement> //define what constitutes equal here;
});
if (existingItem) {
vm.administrators.remove(existingItem);
vm.administrators.push(vm.adminToAdd());
}
else {
//case where it wasn't in the array
}

Compare a string against a list of newly created booleans without looping,

I have created a list of new booleans in javascript, belonging to boolean values in different languages (true, false, verdadero, falso, ratt, fel, etc...)
I have done so with:
var false_swedish = new Boolean("fel");
and so on with many others.
I am trying to code a small text game as a kind of puzzle to learn (I am very beginner), so I am stuck here. Now my goal is: Since I have a list of 10 new booleans, how can I compare them against a string (what the user writes using a prompt)?
I was thinking first about creating an array with all the new words and then compare them with the string, but that defeats the point of declaring them as new Booleans and finding out if the user input is boolean, and here I am not very interested in the final result but more in the process of doing it (as I said, is just an exercise to learn)
I got as far as creating a function that checks if a variable is a Boolean, basically using:
if (value.constructor == Boolean ){
return true;
and then using that function to add a new method to String with prototype, so I can check against the string provided by prompt. But of course, that function is useless, because it's assuming that the variables might be booleans, and they are not. They are always strings...
Am I trying to complicate it too much?
Thanks for any ideas
Yes, you are trying to complicate it too much.
new Boolean("any string") is useless, since with any non-empty string the resulting variable would be true. If your goal was to check whether the user entered 'true or 'false' only, the best solution would be to compare his input to 'true'. But in case there are lots of possible inputs, you can use an object:
// this object contains every string value you want to include in your script defined by a number
var predefinedValues = {'true': 1, 'false': 0, 'verdadero':1, 'falso':0};
// i assume userInput contains user input
if(predefinedValues[userInput] == 1) {
//true
}
else {
//false or not found in array
}

Categories

Resources