Using Function Variable to Retrieve Object Literal Value [duplicate] - javascript

This question already has answers here:
Variable as the property name in a JavaScript object literal? [duplicate]
(3 answers)
Closed 6 years ago.
I have a function that converts an object literal response data into an array:
From: [{"_id":"1","rating":7},{"_id":"2","rating":3}]
To: [7,3]
function createArray(fieldVar, responseData) {
var newArray = responseData.map(function(data) {
return data.fieldVar // fails here because I am trying to use the fieldVar variable
});
return newArray
};
I call the function like this:
createArray('rating',response.rating_x)
This fails because of the data.fieldVar If I hardcode the call to data.rating it works correctly.
How do I pass in the 'rating' or any other name on the function call?

Try it with brackets
function createArray(fieldVar, responseData) {
var newArray = responseData.map(function(data) {
return data[fieldVar] // access with brackets
});
return newArray
};
When using the dot-notation, the property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), not starting with a number. When you're using variables, you need to use bracket notation, else data.fieldVar would point to the property 'fieldVar' which probably doesn't exist. This is because the variable that you intended to access is not evaluated, but instead treated as a normal "string".
More informations on MDN: Property accessors

Related

How to to make a varargs statement in javascript [duplicate]

This question already has answers here:
JavaScript variable number of arguments to function
(12 answers)
Closed 1 year ago.
In javascript I am in situation where i need to make variable arguments based on a length of an array, below is an sample code
function getValesList(json){
return getValues(json[0])+getValues(json[1])+getValues(json[2]);
}
function getValues(json1){
let valueList = Object.values(json1);
let valueListPipe = valueList.join("|");
return valueListPipe+lineSeparator;
}
where json is an array of JSON objects and I need to make a pipe delimiter file based on the length of incoming array. How to make it dynamic where I can do like a varargs in JAVA
If you're just passing N arguments of the same type, you can use the rest feature of Javascript for function arguments.
function getValuesList(...json){
return json.map(j => getValues(j)).join("");
}
This allows you go pass any number of separate arguments as in getValuesList(o1, o2, o3, o4) and the json parameter within your function will automatically be an array of however many arguments were passed.

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

# symbol in the key in JSON is giving error while accessing it [duplicate]

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 4 years ago.
I have following JSON element.
"myObj":[
{
"#type":"xzy",
"data" :"pqr"
}
]
I am accessing a value inside the array using the key as follows
var data = myNode.filter(x => x.#type=='xyz').map(y=>y.data)
But I canot do it becuase of the # symbol in the key. I tried surrounding it with '
var data = myNode.filter(x => x.'#type'=='xyz').map(y=>y.data)
but again it fails. # symbol is valid in JSON. So, I should be able to access it. How can I do this in Javascript? Appreciate your input
Instead of:
var data = myNode.filter(x => x.'#type'=='xyz').map(y=>y.data)
Use this:
var data = myNode.filter(x => x['#type']=='xyz').map(y=>y.data)
Square bracket notation allows access to properties containing special characters and selection of properties using variables.

Use a variable inside a dictionary (associative array) in javascript [duplicate]

This question already has answers here:
Is it possible to define a dynamically named property using object literal in JavaScript? [duplicate]
(7 answers)
Closed 8 years ago.
I have this particular script which uses a javascript dictonary
var z= 'Bingo';
var fruit={ 'Bingo' :1};
var fruit2={ z :1};
alert(fruit[z]);
alert(fruit2[z]);
alert(fruit2['z']);
The first alert gives the expected value 1. However, the second alert gives the alert value as "undefined" and third alert gives the output as 1. Is there a way to use a variable inside a dictionary, ie. can we specify the javascript interpreter to read z as a variable rather than as string 'z'?
Thanks!
Yes, you can do this easily, but not inside an object literal. Property names in object literals are taken literally. They are not variable names. JavaScript quotes them implicitly if you don't quote them.
For example, these two object literals are the same:
{ a: 1 }
{ 'a': 1 }
To use a variable, you need to use [] notation outside an object literal:
var z = 'Bingo';
var fruit2 = {};
fruit2[z] = 1;

Adding custom variables to an object [duplicate]

This question already has answers here:
How to convert string as object's field name in javascript
(5 answers)
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
Suppose I have an object obj which has some variables in it. What I want to do is to add a new variable which has a name i gave as a parameter.
For example:
var obj=
{
number:8
}
function AddField(field_name,obj)
{
//some magical code here
}
If I call
AddField('name',obj);
i want to be able to do
obj.name='Apple'
after calling this function.
Any ideas?
Use square brackets notation:
obj[field_name] = value;
REF: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId
Use the bracket notation:
obj[field_name] = void 0;
This creates a new property with an undefined value.
If obj is already defined, you can just do obj.field_name = null or obj["field_name"] = null.
I wouldn't set any value to undefined even though the language allows for that, simply for a semantic issue: undefined means "this property/variable has not been defined" and null means "this property/variable has no value".

Categories