Javascript function push problem - javascript

i've following JS function.
responseData:function(resp){
this.jsondata = eval('(' + resp + ')');
this.propList = [];
for (var i = 0;i<this.jsondata.length;i++) {
for (obj in this.jsondata[i]) {
alert(obj); //shows the property name of obj
this.propList.push({
obj : this.jsondata[i][obj] //insert only simple obj string
});
}
}
return this.propList;
}
I want to insert in my propList the property name and the value, but instead inserting the property name this function inserts simple 'obj' as a string. What i'm doing wrong?
greetings
Stefan

Change the loop to,
for (obj in this.jsondata[i]) {
alert(obj); //shows the property name of obj
var item = {};
item[obj] = this.jsondata[i][obj];
this.propList.push(item);
}
When you use object-literal to create an object the property names are not evaluated as variables. To specify the name of an objects property using a variables current value, you must use the obj[variable] format. This will create a property within obj whose name will be the same as current value of variable.

Related

Using a string stored in a variable as a name for another variable

I want to concatenate a string passed as argument with another word and then use it as a variable name for an array. Is this allowed?
function getFromSomewhere(arg1) {
string newName = arg1 + "sampleWord";
var (use NewName here) = [];
}
Not allowed, unfortunately. Variable names, such as newName, that we see are rid of at compilation time for optimization. Your machine will have no use for it's name newName during runtime, which is when you're trying to assign the name to it.
You could use an object with the wanted fruits as key for the array, like in the example.
The object is easy to access and to maintain.
var array = ["apple", "banana", "grapes"],
prices = {};
array.forEach(function (k) {
prices[k] = [];
});
prices.apple.push(1, 10, 3);
console.log(prices.apple[2]);
console.log(prices);
You can use newName as the name of a property
function getFromSomewhere(arg1) {
var myVariableNamedAtRuntime = [];
string newName = arg1 + "sampleWord";
myVariableNamedAtRuntime[newName] = [];
}
and then access the array as ...
myVariableNamedAtRuntime[newName]
There is no way you can add new variables to the function definition after the function is defined.. However you can always add new properties to the function object defined or it's prototype and you can access them as follows;
function getFromSomewhere(arg1) {
var newName = arg1 + "_sampleWord_";
this.getFromSomewhere.varName = newName + "test";
this.getFromSomewhere.prototype.varName = newName + "best";
console.log(this.getFromSomewhere.varName);
console.log(this.getFromSomewhere.prototype.varName);
}
getFromSomewhere("test");
You can add the variable to the window object:
function getFromSomewhere(arg1) {
var newName = arg1 + "sampleWord";
window[newName] = [];
}
getFromSomewhere("blip");
console.log(blipsampleWord); // You'd get []
Yes it is possible. But no, you dont want to do that. Dynamic variable names are always a sign, that you should use an object instead. In this case i think you could simply map your array of strings to an array of objects:
function namesToObj(arr){
return arr.map( name => ({
name,
price:10
}));
}
namesToObj(["banana","tomato"])
/*results in
[{name:"banana",price:10},{name:"tomato",price:10}]
*/

How to fetch a value from JavaScript array?

I have a JavaScript array and I want to get the value of last name from it.
Can anyone tell how to get that from this array example:
var result = [{"FirstName":"paapu","LastName":"gandhi"}];
You have an array containing an object, so you have to retrieve the object by doing:
var myObj = result[0]
And then get the LastName property by:
var lastname = myObj.LastName
Get the first object.
var obj = result[0];
Refer to the property of the object:
var prop = result[0].FirstName;
If property name comes dynamically, that is, from a variable, use square bracket notation.
var myVar = "FirstName";
var prop = result[0][myVar];

how to find the props in obj with variable name in javascript

I am passing my string to the below function.
$scope.sort= function(query){
console.log(query); // results "name";
$scope.resultset.sort(function(a, b) {
return parseFloat(b.query) - parseFloat(a.query); //results undefined;
});
};
where b and a are my objects in resultset Array.
How to find the props in obj with variable name?
I suppose you mean accessing an object property with a dynamic name.
In javascript, you can access any object propert with an array-like notation:
b.query
is equivalent to :
b["query"]
So you could do :
var property = "query";
var value = b[property];

javascript access object with variable name

I am trying to access an object but the name is variable. So:
I have object41, object42 and object43. I want to access object42.
id = 42;
something like this:
object+id.function();
I have searched and found how to assign objects with variable names and how to access properties with variable names but I can't figure out how to access objects with variable names.
Is this something obvious that I am missing?
If these objects are global, you can access them via the window object, and then call your function on the resulting object.
var id = 42;
window["object" + id].function();
Try using eval
// Sample object
function X(id) {
this.value1 = "A" + id;
this.function = function f(value){
alert(value);
};
return this;
}
// n number of object created
var object1 = new X(1);
var object2 = new X(2);
// iterate over all object
for (i=1; i<=2; i++) {
var expr = "object"+i+".function(object"+i+".value1)";
eval(expr);
}
Here a jsfiddle : demo

Using variable name in JS object?

I defined a variable which will get user's input:
var input = USER_INPUT;
then, I create an object which will use this input as an variable name inside the object:
var obj = { input: Car.newCar(...)}
Then, I try to access the obj[input], but it returns to me undefined. Is it so that in javascript, I can not use variable as an object's variable name?
If I would like to define a object which has vary variable name and variable value, how can I do?
So I guess you want the store the input under a key named after the input itself.
You can assign the value returned by Car.newCar() by using the [] method:
var input = "some text";
var obj = {};
obj[input] = Car.newCar();
Sorry changed my answer after re-reading the question
var USER_INPUT = 'something';
var obj = {};
obj[USER_INPUT] = 'value';
obj.something ; //# => value
obj['something'] ; //# => value
obj[USER_INPUT]; //# => value

Categories