javascript Assign the array inside variable - javascript

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:[]
}

Related

How to access variable value inside a function in javascript

I have searched on the website for solutions, but I have had no luck.
I need to make this data global. My code is present below:
function val() {
var plans = #json($plans);
var id = document.getElementById("plan_id").value;
plans.forEach(function(element) {
if (id == element.id) {
var i = element.amount;
return i;
}
});
}
var obj = val()
console.log(obj)
After I log that, it wont give any values but if I log inside the foreach, I will get the amount. Pls how can I access data inside foreach
Your function needs to return a value if you want to log it outside like this.
function val() {
const plans = #json($plans);
const id = document.getElementById("plan_id").value;
return plans
.filter(element => id === element.id)
.map(element => element.amount);
}
const obj = val()
console.log(obj)
You are not returning anything from the function and return inside forEach is always undefined. Use find
function val() {
var plans = #json($plans);
var id = document.getElementById("plan_id").value;
return plans.find(element => id === element.id).amount;
}
var obj = val()
console.log(obj)
This would on change get the amountValue from based on what ID you have selected.
var amountValue = null;
function val() {
var plans = #json($plans);
var id = document.getElementById("plan_id").value;
for (i = 0; i < plans.length; i++) {
if (id === plans[i].id) {
amountValue = plans[i].amount;
return amountValue;
}
}
}
var obj = val()
console.log(obj)
Thanks everyone, I have fixed my issue, but I follow another process.
I actually get the amount using onclick

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

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.

Cannot read property 'push' of undefined

I am trying to push data attribute value into array parameter but it throws the above error on the line parameter[parent].push(parent);
var parameter = {};
var currentTabSelected = "";
var parent = "";
$("#categories").on("click", ":checkbox", function () {
if($(this).is(":checked")) {
parent = $(this).data("parent");
console.log(parent)
if (!(currentTabSelected in parameter)) {
parameter[currentTabSelected] = []
}
var found = $.inArray($(this).val(), parameter[currentTabSelected]) > -1;
if (!found) {
parameter[currentTabSelected].push($(this).val());
parameter[parent].push(parent);
console.log(parameter)
}
} else {
var index = parameter[currentTabSelected].indexOf($(this).val());
var parent_index = parameter[parent].indexOf(parent)
if (index > -1) {
parameter[currentTabSelected].splice(index, 1);
parameter[parent].splice(parent_index , 1);
}
}
})
what can i do to overcome the above problem?
If parameter is an object you should create keys before using them.
You are trying to access the key which is not present in the parameter.
For example , make sure your object contains currentTabSelected and parent:
parameter[currentTabSelected] = []
parameter[parent] = []
After initializing currentTabSelected and parent you can perform operation on parameter[currentTabSelected], parameter[parent].
I suffered from the same issue few days ago, the solution is directly related with the 'this' keyword. Your 'this' is referring to another scope that your variable is not a part of. You might want to do a
var that=this;
Or if you're comfortable with ES6, you can use the arrow function syntax.

Passing through array that is in an object into a function

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'

Categories

Resources