Passing through array that is in an object into a function - javascript

I want to pass an object into a function as a parameter, and assign things to properties of that object, then those would be accessible outside of the function. But I am not to clear on how it is done.
At first I thought it could be done using callbacks, but it was made clear to me that JavaScript does not work that way. I eventually managed to get it working, and the undefined error messages went way. But I wanted to now pass an array through the function. How can this be done? This is what I've done so far, but it doesn't seem to be working.
var journey = {};
journey['waypointsArrayItem'] = new Array();
setupAddress(journey)
function setupAddress(journey) {
var waypointsItem = $('.timeline-item.active-item > .timeline-status > .waypoints').text().substring(4);
journey.waypointsArrayItem = [];
journey.waypointsArrayItem = listToArray(waypointsItem, ', ');
for (var i = 0; i < waypointsArray.length; i++) {
journey.waypointsArrayItem[i] = journey.waypointsArrayItem[i];
}
}

You are copying array items to themselves. Copy from the waypointsArray array to the journey.waypointsArrayItem array:
function setupAddress(journey) {
var waypointsItem = $('.timeline-item.active-item > .timeline-status > .waypoints').text().substring(4);
var waypointsArray = listToArray(waypointsItem, ', ');
for (var i = 0; i < waypointsArray.length; i++) {
journey.waypointsArrayItem[i] = waypointsArray[i];
}
}
Depending on what you need, you could also just replace the entire array:
function setupAddress(journey) {
var waypointsItem = $('.timeline-item.active-item > .timeline-status > .waypoints').text().substring(4);
journey.waypointsArrayItem = listToArray(waypointsItem, ', ')
}

Assigning properties to an object in a function is the same as assigning properties outside of a function.
function addName(obj, name) {
obj.name = name;
}
var bob = {};
console.log(bob.name); // undefined
addName(bob, 'Bob');
console.log(bob.name); // 'Bob'

Related

AngularJS bind object parameter to object var

I have some code like this
$scope.grabItems = function(data) {
data.model = ['test'];
console.log($scope.ui.projects);
}
$scope.ui.projects = [];
$scope.grabProjects = function() {
$scope.grabItems({model: $scope.ui.projects});
}
I'm trying to change the $scope.ui.projects variable using the parameter of another function (this is so that I can write an abstract grabItems function using any variable).
The problem is it looks like the data.model = ['test'] isn't changing the $scope.ui.projects variable at all but is creating a brand new variable.
How would I modify the outer variable in a reusable way like this?
Note that $scope.ui.projects could potentially be any variable.
You are not actually not changing $scope.ui.projects, Try like this
$scope.grabItems = function(data) {
data.model = ['test'];
console.log($scope.ui.projects);
}
$scope.ui.projects = [];
$scope.grabProjects = function() {
$scope.grabItems($scope.ui.projects);
}
If it's not clear, share what is your expected object.
You could achieve it by pushing items into the array:
$scope.grabItems = function(data) {
if(!angular.isArray(data.model))
throw new Error('Array expected');
data.model.length = 0; // empty array
data.model.push('test'); // push items
console.log($scope.ui.projects);
}
$scope.ui.projects = [];
$scope.grabProjects = function() {
$scope.grabItems({model: $scope.ui.projects});
}

javascript Assign the array inside variable

I am trying to assign a array inside a variable in javascript. But i am getting error like this. Could you please correct me where i have missed.
"TypeError: newItems.json is undefined"
var newItems = [];
if ($$('.selectvals:checked').length > 0) {
var i=0;
$$('.selectvals:checked').each(function (e) {
var row = e.parentNode.parentNode;
var jsonVals = row.down('.jsonval').value;
var jsonPaymentVals = row.down('amount').value;
newItems['json'][i] = jsonVals;
newItems['amount'][i] = jsonPaymentVals;
i++;
});
}
You need initialize right it, like this:
var newItems = {
json:[],
amount:[]
}

By using array.push method elements are getting added but it's overriding last object as well

I'm facing an weird issue here every time I am pushing obj to the array arrays length is increasing as expected but the object which I am push at last that is overriding all other object, I am not able to identify my mistake so please help me. Thanks in Advance please check following code.
var tablehead = {};
var experimentsData = [];
var obj = {};
var remoteSheet = response.result.values;
remoteSheet.filter(function(innerArrayItem) {
if (i == 0) {
tablehead = innerArrayItem;
i++;
} else {
$.each(tablehead, function(key, value) {
obj[value] = innerArrayItem[key];
});
experimentsData.push(obj);
}
});
Because you're pushing the same object everytime. obj is only created once and at each iteration you override data you put in it at the previous iteration.
var experimentsData = [];
// var obj = {}; <-- don't define obj here
var remoteSheet = response.result.values;
remoteSheet.filter(function(innerArrayItem) {
if (i == 0) {
tablehead = innerArrayItem;
i++;
} else {
var obj = {} // <-- define it here
$.each(tablehead, function(key, value) {
obj[value] = innerArrayItem[key];
});
experimentsData.push(obj);
}
});
Also, filter is a bad way of iterating an array, I recommend switching to a basic for loop.

Pushing object into array erases instead of adding

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
}
}
};

Update happens only on the last row, instead of first

function createTextFields(obj) {
for (var i = 0; i < obj.length; i++) {
var dataDump = {};
for (var key in obj[i]) {
var textField = Ti.UI.createTextField(pm.combine($$.labelBrown, {
left: 200,
height:35,
value:obj[i][key],
width:550,
keyboardType:Ti.UI.KEYBOARD_NUMBER_PAD,
layout:'horizontal',
backgroundColor:'transparent',
id:i
}));
dataDump[key] = textField.value;
var callback = function (vbKey) {
return function (e) {
dataDump[vbKey] = e.source.value;
};
}(key);
}
globalData.push(dataDump);
}
}
I am using the simlar code for Adding the data and it works fine. I posted the problem yesterday and it got resolved...
Last Object is always getting updated?
Now when i go to edit page, it shows me four text fields or number of text fields added... now when i edit something and click on save... the value get's updated on the fourth or the last TextFields Object...
Don't define functions inside loops. Computationally expensive and leads to problems, like this one. Here's a fix that should solve it:
function createTextFields(obj) {
var callback = function (vbKey, localDump) {
return function (e) {
localDump[vbKey] = e.source.value;
};
}
var i;
var max = obj.length;
for (i = 0; i < max; i++) {
var dataDump = {};
for (var key in obj[i]) {
dataDump[key] = textField.value;
var callBackInstance = function(keyn, dataDump);
}
globalData.push(dataDump);
}
}
JavaScript does not have block level scope, so your variables dataDump and callback, though "declared" inside for-loops actually belong to the function. As in, you're saving a value to dataDump, then you're overwriting it, each time you go through the loop. Which is why finally only the code that operated on the last value remains.
Take a look at What is the scope of variables in JavaScript? too.

Categories

Resources