Pushing object into array erases instead of adding - javascript

I have a function like this :
$scope.saveSearch = function () {
var alreadyExist = false;
for (var i = 0; i < $scope.savedSearch.length; i++) {
if (JSON.stringify($scope.searched) === JSON.stringify($scope.savedSearch[i])) {
alreadyExist = true;
break;
}
}
if (!alreadyExist) {
$scope.savedSearch.push($scope.searched);
localStorage.setItem("savedSearch", JSON.stringify($scope.savedSearch));
}
};
Before that : $scope.savedSearch = [];
$scope.searched = {
IS: "",
area: "",
block: "",
type: "",
level: ""
};
The values in $scope.searched object are initialized and then modified by the user.
My problem is :
$scope.savedSearch always contains only the last pushed object. Instead of adding the object to the array, it just replaces the current object.
I don't understand why.

You'll want to change your push line to:
$scope.savedSearch.push(angular.copy($scope.searched));
I believe your problem is that objects are passed by reference. Since the object you have in the savedSearch is always pointing to the exact object you're searching, alreadyExist will always be true.

My guess is that the object reference is being stored in your array, not the actual object itself. Because of this, any subsequent calls to push the object to your array will not work because the object reference already exists in the array. It's merely updated.
Try this instead. Use angular.copy() to create a deep copy of the object and push the copy to your array. See if that works.
if (!alreadyExist) {
$scope.savedSearch.push(angular.copy($scope.searched));
localStorage.setItem("savedSearch", JSON.stringify($scope.savedSearch));
}

You are pushing the Object outside of the for so only 1 element get pushed in try move it inside the for and every object which doesnt already exist will be pushed in
$scope.saveSearch = function () {
var alreadyExist = false;
for (var i = 0; i < $scope.savedSearch.length; i++) {
if (JSON.stringify($scope.searched) === JSON.stringify($scope.savedSearch[i])) {
alreadyExist = true;
break;
}
if (!alreadyExist) {
$scope.savedSearch.push($scope.searched);
localStorage.setItem("savedSearch", JSON.stringify($scope.savedSearch));
}
}
};
easier way would be to just
$scope.saveSearch = function () {
var alreadyExist = false;
for (var i = 0; i < $scope.savedSearch.length; i++) {
if (JSON.stringify($scope.searched) != JSON.stringify($scope.savedSearch[i])) {
$scope.savedSearch.push($scope.searched);
localStorage.setItem("savedSearch", JSON.stringify($scope.savedSearch));
}else{
break
}
}
};

Related

angular.isUndefined() function working abruptly

angular.module("customFilters", [])
.filter("unique", function () {
return function (data, propertyName) {
if (angular.isArray(data) && angular.isString(propertyName)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyName];
console.log(angular.isUndefined(keys[val]))
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
}
});
i am new to angularjs and facing problem with angular.isUndefined() function.
So the issue is like i am adding properties to an object with the help of for loop and also checking that if a particular property is already defined for the object, if the property is defined then i am not adding that property to the object but when i am using angular.isUndefined() to check the property it returns false even when the property is there in the object and keeps doing so two times and for the third time it returns true when i call angular.isUndefined().
Please help in here.

Why Javascript object didn't change?

Can someone explain me this strange js behavior ?
All of this is in AngularJS.
I have helper function in my main app.js to simply return element from an array by its id:
var MyLib = MyLib || {};
MyLib.helpers = {
find: function(needle, stack) {
for (var i = 0; i < stack.length; i++) {
if(stack[i]._id === needle)
return stack[i];
}
return false;
}
}
Then I have factory and function to handle database change:
// categories are grabbed from db
var categories = [some array of objects];
// change is object returned from database that has all info about object as well as new object itself
function handleChange(change) {
var _category = MyLib.helpers.find(change.id, categories);
// if deleted, that part is ok
if(change.deleted) {
var idx = categories.indexOf(_category);
if(idx !== -1) {
categories.splice(idx, 1);
}
} else {
// if updated that part is weird
if(_category) {
_category = change.doc;
}
// if newly added that part is ok
else {
categories.push( angular.copy(change.doc) );
}
}
}
Why when I try to update element grabbed from categories array doesn't update in categories array ?
// categories ARE NOT updated after this
_category = change.doc;
and only when I refer to categories by index like this:
// categories ARE updated after this although _category is returned from this array by index (find function)
var idx = categories.indexOf(_category);
categories[idx] = change.doc;
I don't understand this...
You are overwriting the variable with a new value and any reference to prior value is gone.
Instead of overwriting the original object value with a new object you could update the existing object using angular.extend()
angular.extend(_category, change.doc);
I didn't analyze everything, but you should always have dot notation.
_category pass by value, and will not change when 'MyLib.hel ...' is changed
var _category = MyLib.helpers.find(change.id, categories);
something.category pass by reference, and will be changed when 'MyLib.hel ...' is changed
var something.category = MyLib.helpers.find(change.id, categories);

JavaScript-- Array Variable getting Updated Automatically

I was writing code for shopping cart function. When ever I add a product to cart, for each product, at first time and additional attribute called quantity gets added.
This is my code:
myStoreCartService.factory('Cart',function() {
var userCart = [];
var cartSummary = [];
var cartConsolidatedData = [];
var currentTotalMaster;
function formCart() {
cartConsolidatedData = [];
var dup = false;
var temp;
for(x in userCart) {
dup = false;
for(z in cartConsolidatedData) {
if(cartConsolidatedData[z].productname == userCart[x].productname) {
cartConsolidatedData[z].quantity = cartConsolidatedData[z].quantity + 1;
dup = true;
break;
}
}
if(!dup) {
// temp = userCart[x];
// temp.quantity = 1;
cartConsolidatedData.push(userCart[x]);
for(y in cartConsolidatedData) {
if(cartConsolidatedData[y].productname == userCart[x].productname) {
cartConsolidatedData[y].quantity = 1;
break;
}
}
}
}
};
return {
addItemToCart: function(cartData) {
console.log(cartData);
userCart.push(cartData);
formCart();
},
retrieveCart: function() {
return userCart;
}
});
Here even the fist item in userCart variable get quantity attribute, however just cartConsolidatedData variable's values should have got the this attribute.
I am stuck bad time here.
I'm not sure I understand your code but I suppose cartData is an object and you push that object to userCart like this
userCart.push(cartData);
then you push the same object to cartConsolidatedData with this command
cartConsolidatedData.push(userCart[x]);
So when you do this:
cartConsolidatedData[y].quantity=1;
You are adding a property to the cartData object and not as you state to the cartConsolidatedData array. Because cartConsolidatedData[y] is a cartData object and since it's a reference it means any change you do to it will also be reflected in the userCart array that points to the same cartData.

store value in JSON on button click

I am new in JSON, i am trying to save data using JSON. I have a list of element with some button when we click the button i want the corresponding value of button are save in JSON. I am also want to compare the title with already exists in JSON.
Demo Here
You can simply use a for loop to check if the element with that title is already there:
function alreadyAdded(itemTitle) {
for (var i = 0; i < objArray.length; i++) {
if (objArray[i].title === itemTitle) {
return true;
}
}
return false;
};
Also, you are not using a json object, just a JavaScript array.
Demo
try this
http://jsfiddle.net/Z3v4g/
var counter = 0;
var jsonObj = []; //declare object
$('.imgbtn').click(function () {
var title = $(this).parent().parent().find('span').html();
var image = $(this).parent().parent().find('img').prop('src');
for( var i=0; i<jsonObj.length; i++){
if( jsonObj[i].title == title ) return false;
};
counter++;
$('#lblCart').html(counter);
jsonObj.push({
id: counter,
title: title,
image: image,
description: 'Example'
});
});
I am assuming you want to store values in an array, and during a button click you want to check if the item already exists in the array. If this is true, then you can use the following code -
var counter = 0;
var jsonObj = []; //declare object
$('.imgbtn').click(function () {
var title = $(this).parent().parent().find('span').html();
var image = $(this).parent().parent().find('img').prop('src');
var match = $.grep(jsonObj, function (e) {
return e.title == title;
});
if (match.length > 0) {
// This title already exists in the object.
// Do whatever you want. I am simply returning.
return;
}
counter++;
$('#lblCart').html(counter);
jsonObj.push({
id: counter,
title: title,
image: image,
description: 'Example'
});
});
Notice that I have declared the array outside the callback function. This ensures that all the invocation of the callback operate on the same array object. Declaring it inside the callback was only making it available for a single callback invocation.
Also note that you are simply using an array to store plain JavaScript Objects.
Demo.
First:
var jsonObj = []; //declare object
This is not a JSON. This is an Array. JSON is just the notation of Javascript Object. To declare a object you should do:
var jsonObj = {};
or:
var jsonObj = new Object();
After this, you can approach what you asked doing this:
var counter = 0;
var jsonObj = new Object();
$('.imgbtn').click(function () {
var title = $(this).parent().parent().find('span').html();
var image = $(this).parent().parent().find('img').prop('src');
if (!(title in jsonObj)) { // if item is not in the object, (title in jsonObj) returns true of false
jsonObj[title] = { // When you have hundreds of items, this approach is way faster then using FOR loop, and if you need to alter the item or get one value, you can just call it by name: jsonObj['ABC'].image will return the path of the image
id: counter,
image: image,
description: 'Example'
}
counter++;
$('#lblCart').html(counter);
} else {
// Do what you want if the item is already in the list
alert('Item already in the list');
console.log(jsonObj[title]);
}
});
DON'T use FOR loops to do what you wan't, it will just slow down your application if the counter gets high.

Returning a private variable in JavaScript

I don't know why console.log(Set.current_index) shows 0 instead of 3.
var Set = (function() {
var set = [];
var index = 0;
function contains(set, e) {
for (var i = 0; i < set.length; i++) {
if (set[i] === e) {
return true;
}
}
return false;
}
var add = function(e) {
if (!contains(set, e)) {
set[index++] = e;
}
}
var show = function() {
for (var i = 0; i < set.length; i++) {
console.log(set[i]);
}
}
return {
add: add,
show: show,
current_index: index
};
})();​
Set.add(20);
Set.add(30);
Set.add(40);
Set.show();
console.log(Set.current_index);
As written current_index just gets the initial value of index - it doesn't mirror any changes to that value because that variable is of primitive type.
If you have a 'reference type' (i.e. an object or array) then changes to its contents become visible in any other variable that references the same object. That doesn't happen with primitive types, they're copied "by value" into the new variables, and changes to the original variable don't affect the copy.
You need to make current_index into a function that returns the current value of index, or write it as a getter which allows you to treat .index as a read-only property by invisibly calling a function to return the current value.
For an example of the latter method (which requires ES5, or shims to replicate the functionality) see http://jsfiddle.net/alnitak/WAwUg/, which replaces your current return block with this:
var interface = {
add: add,
show: show
};
Object.defineProperty(interface, 'index', {
get: function() {
return index;
},
enumerable: true
});
return interface;
Javascript always passes by value except when a variable refers to an object. So your initialization of current_index just gets the initial value of index rather than permanently pointing to the variable, so after that initialization, the two variables are on their separate ways therefore incrementing index doesn't increment current_index.

Categories

Resources