Comparing two Objects not working? [duplicate] - javascript

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 4 years ago.
I'm facing an issue with comparing two Objects.
I'm comparing an incoming Object, with an Object Array,
to see if the Object is already in the array.
I tried two methods:
(betTemps is the Array of Objects, tempBet is the current object which should be compared.)
var duplicate = false;
for (let bet of this.betTemps) {
console.log(tempBet);
console.log(bet);
if(bet === tempBet) {
console.log("reached");
duplicate = true;
break;
}
}
The if afterwards:
.. else if(duplicate){
alert("The Bet is already in the List");
} ...
Console Output after adding an Object which is already in the Array:
Console Output Screenshot
As you can see, they are equal, still the other Object is added to the array.
I tried using this method too with indexOf:
if(this.betTemps.indexOf(tempBet) > -1){
alert("The Bet is already in the List");
}
Console Output after adding an Object which is already in the Array:
Console Output Screenshot
PS:
The code before the comparison:
addBet(bet, index){
var tempBet = Object.assign({}, bet);
var select = (document.getElementById('select'+index)) as HTMLSelectElement;
select = select.options as HTMLSelectElement;
let count = 0;
tempBet.category = [];
for(let i = 0; i < 3; i++) {
if (select[i].selected) {
tempBet.category.push(select[i].value):
count++;
}
}
The code after the comparison:
if (count == 0) {
alert("There has to be at least one Category choosen!");
} else if(duplicate <- This part changes individually which method you use ->){
alert("The Bet is already in the List");
} else {
this.betTemps.push(tempBet);
}

The best way to check if an object is in an array is using the array includes function:
Like if I want to check if A object is in B array I would check
(A === B.includes(A))

Related

Check if value exists in array javascript [duplicate]

This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A
Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))
You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')
You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.

I have an issue with removing an object key with a for in loop

I'm using a for x in loop to check if a value is == to [] and if so remove the property using remove but it just does not seem to work.
const whosOnline = (a) => {
var obj = { online:[],
offline:[],
away:[] };
for(let i = 0; i < a.length; i++){
if(a[i].lastActivity > 10 && a[i].status == 'online'){obj.away.push(a[i].username)}
else if(a[i].status == 'offline'){obj.offline.push(a[i].username)}
else{obj.online.push(a[i].username)}
}
for(let x in obj){
console.log(obj[x])
if(obj[x] === []){delete obj[x]}}
return obj
}
you were close, however you also need to reference the array index for each object key value. Comments explaining this in the code below.
var obj = { online:[],
offline:[],
away:[] };
for(var x in obj){
if(!obj[x][0]){ // The 0 is the index inside the online array, next loop it will be the offline array and then the away array.
console.log('The array is empty');
// Do what you want to do now that it is empty
// This will continue to loop through and check the value of all the keys in the object.
}
}
console.log('done');
Good luck -
Mitch from
https://spangle.com.au
Using some debugging (simply testing if a console.log gets printed for instance) you find that your if-condition is never true.
This is because you test if an array equals a newly created empty array. This can never be the case, because objects are compared by object reference instead of value.
Instead you want to probably test to see if your array is empty by doing ‘if(obj[x].length===0)’ (or shorter: ‘if(!obj[x].length)’)

How to check if value existed in array or not?

I dont want to push duplicate values into selectedOwners, so in below code user is selecting owner if owner already existed in selectedOwners array i dont want to push , How can i check that to avoid duplicate values in an array ?
ctrl.js
var selectedOwners = [];
$scope.addProcessOwner = function(dataItem){
var selectedOwner = {
fullName: dataItem.fullName,
workerKey: dataItem.workerKey
}
if(selectedOwners.indexOf(selectedOwner) !== -1) {
selectedOwners.push(selectedOwner);
}
console.log('WORKER DATA',selectedOwners);
}
You can use Array.prototype.some method
The some() method tests whether some element in the array passes the test implemented by the provided function.
var isExists = function(e) {
if (e.fullName == selectedOwner.fullName
&& e.workerKey == selectedOwner.workerKey) {
return true;
}
}
if (!selectedOwners.some(isExists)) {
selectedOwners.push(selectedOwner);
}
The use of Array.indexOf is obvious for simple types like strings and numbers.
However, when you are looking for an object, you have to pass the exact same object. A different object with all the same properties and values will still not work. Think of the array as containing pointers to the objects and you must look for the same pointer.
Instead you will need to write your own method to compare the owners for equality and loop through the array doing this check.
Try wrapping your "if" logic in a for-loop .
Example
//Following code loops through array and check for already existing value
for(var i = 0; i < selectedOwners.length; i++){
if(selectedOwners.indexOf(selectedOwner) !== -1) {
selectedOwners.push(selectedOwner);
}
}

Check the object already exists in array in Vue.js

I have a data:
data: function() {
return {
conversations:
[
]
}
}
I'm getting my data from response object: response.data.conversation
Is there a way to check this.conversations already contains response.data.conversation?
To build on your answer, if you're already using underscore or lodash you can use its _.any()/_.some() function:
var exists = _.any(this.conversations, function(conversation) {
return _.isEqual(conversation, response.data.conversation);
})
You can also use Array.prototype.some to do the same kind of thing:
var exists = this.conversations.some(function(conversation) {
return _.isEqual(conversation, response.data.conversation);
})
The benefits of these over your solution is that they'll return as soon as they find a match (instead of iterating through the whole array), though you could easily update your code to break out of the loop early.
Also, while _.isEqual() is cool, you might be able to get away with some simple property comparisons (if your objects are flat enough or, even better, you have a key that uniquely identifies a conversation) to determine if two objects are equivalent:
var exists = this.conversations.some(function(conversation) {
return conversation.id === response.data.conversation.id;
})
I figured it out:
Used underscore.js.
Iterate trought all objects in array and compare them with _.isEqual(a,b)
function
var count=0;
for(var i=0; i<this.conversations.length; i++ ) {
if(_.isEqual(this.conversations[i], response.data.conversation)) {
count++;
}
}
Then check the value of count variable:
if (count == 0) {
//Add element to array
this.conversations.push(response.data.conversation);
} else {
console.warn('exists');
}

How to check whether a given string is already present in an array or list in JavaScript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?
I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?
In javascript you have Arrays (lists) and Objects (maps).
The literal versions of them look like this:
var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object
if you which to figure out if a value exists in an array, just loop over it:
for(var i=0,len=mylist.length;i<len;i++) {
if(mylist[i] == 2) {
//2 exists
break;
}
}
if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:
if(mymap.seats !== undefined) {
//the key 'seats' exists in the object
}
if(mymap.seats == 2) {
//the key 'seats' exists in the object and has the value 2
}
Array.indexOf(element) returns -1 if element is not found, otherwise returns its index

Categories

Resources