object-reference as string in javascript [duplicate] - javascript

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 5 months ago.
There is a way to pass a string in a function to other function and this string is a reference to an object in this other function?
function fun1 (structure){
obj = [{"header":{"orderNumber": a, "item": 1}}, {"header":{"orderNumber": b, "item": 1}}]
newObj = obj[0].structure
console.log(newObj)
//first call a
//second call 1
}
//first call
function fun2(){
structure = 'header.orderNumber'
fun1(structure)
}
//second call
fun2(){
structure = 'header.item'
fun1(structure)
}
What I want is a dynamic way to access an object by creating a string.
For example in the block of code obj.header.item.description and this is valid. I would like to pass a string in this string somehow make a reference to the object so I can get the value.

One way you could accomplish this would be by storing all of the object references in a Map (MDN) structure where the key is a string and the value is the object reference in question.
I should say that even though I don't know your exact use case, this is what you would call a "stringly typed" solution which is generally not the best idea.

Related

How to destructure an object into parameter names [duplicate]

This question already has answers here:
Is there a way to provide named parameters in a function call in JavaScript?
(12 answers)
How to get function parameter names/values dynamically?
(34 answers)
Closed 4 years ago.
I have many functions defined elsewhere that look like this
export function foo(bar1, bar2, bar3, ...) {
// does stuff
}
In the module I am working on I am passed both the function above and an object containing the parameters like this:
// params = {
// bar1: bar1Value,
// bar2: bar2Value,
// bar3: bar3Value,
// ...
// }
function myFunc(foo, params) {
}
I need to call func with the params in the correct order. It is an object not an array so I can't rely on the property order, I need to match up the params to the signature of the function. Is this possible?
Edit to add: There are hundreds of functions that can be passed in, I am trying to avoid refactoring them all, but it seems that it is impossible to look up the parameter names directly. However I've found this which shows it can be done by breaking down the function as a string.
You can access the properties of an object (like "params") either like
params.bar1 or like params["bar1"] and you can get the names of the properties by using Object.keys(params), if thats what your asking for.
See also https://www.w3schools.com/js/js_object_properties.asp and https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

JavaScript: store function method to variable [duplicate]

This question already has answers here:
JavaScript Function Context Incorrect
(3 answers)
Closed 7 years ago.
I have a variable a that can be either an object or an array of objects. I have an array array.
I want to append a to array, so I thought of using either Array.prototype.push.call or Array.prototype.push.apply with a ternary operator as follows:
var a = "hello"; // or var a = ["hello", "world"];
var array = [];
var append = ($.isArray(a)) ? Array.prototype.push.apply : Array.prototype.push.call;
append(array, a); // Uncaught TypeError: undefined is not a function
($ being jQuery)
I'm new to JavaScript and I guess there is a good reason why this doesn't work but I couldn't find it. Can't apply or call be assigned to a variable? (They are not real functions?) Or is something missing on the call to append()?
Note: I know I could do this with if/else but I'd rather like to understand why I can't assign these methods to a variable and call it.
Minor additional question: I want to do this because I get a from a JSON API and if I understand correctly, JSON can't contain arrays of one single object. Although I feel that what I'm trying to do must be very common, I also couldn't find how other developers deal with this. Is there a better way than testing whether a is an array or not and use apply() or not accordingly?
This happens because call and apply are instance methods. They are critical to the context object this.
Eventually you should execute append.call(Array.prototype.push, array, a) because call or apply need function push to be passed as this
You don't need any if, just use concat
var array = [];
var a = "hello"; // or var a = ["hello", "world"]
array = array.concat(a);

Do Javascript variable assignments work by reference? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I have a question about referencing objects in javascript.
Say I have a variable that is some object (lets say json) and it is called objOne - (var objOne = someJSONObject;).
If I go ahead and declare
var objTwo = objOne;
will I have two references to the same Object? Kind of like a c pointer?
To sum it up :
assignements are done by value
you never manipulate objects, only object references
This means that
you'll have two references to the same object (you can check that by changing a property of the object)
when you're passed in a variable the value of a primitive, changing your variable doesn't change other variables
EDIT : as it's a duplicate I'll delete this answer in a minute to allow a proper closing if there's no other answer. Please vote to close.
Yes, objects are passed by reference:
function changeVal(obj){
obj.value = "bar"
}
(function checkRefs(){
var myObject = {
value: "foo"
};
alert(myObject.value);
changeVal(myObject);
alert(myObject.value);
})();

Get the name property of a variable [duplicate]

This question already has answers here:
Get variable name. javascript "reflection"
(4 answers)
JavaScript: Get Argument Value and NAME of Passed Variable [duplicate]
(7 answers)
Closed 8 years ago.
I was wondering if it's possible to get the name of a variables in javascript or JQuery.
Suppose that I declare a variable in javascript like:
var customerNr = "456910";
If a function receive a variable, how can i return the name of the variable?
For example:
function getNameOfVariable(someVariable){
//return name of someVariable;
}
If I call this function like this:
getNameOfVariable(customerNr);
The function has to return a string whose value is "customerNr".
How can I do this in jquery or javascript? Some kind of reflection?
That is simply not possible!
The passed parameter doesn't even have to have a name. It could be a return value of a function or a raw literal (like "string" or 3).
No, this is not possible. Only values are transferred for primitive data types, not references, so how would you know what the "name" of the variable is? For example:
var customerNr="456910";
var customerNrAfterProcessing=customerNr;
getNameOfVariable(customerNrAfterProcessing);
Would it return customerNrAfterProcessing or customerNr?
However, you can imitate this behavior with objects.
var variableName = someMethodThatDeterminesVariableNameOrJustAConstantIfYouPrefer();
var myVariables={};
var myVariables[variableName]={};
myVariables[variableName].value="456910";
myVariables[variableName].variableName=variableName;
function getNameOfVariable(someVariable){
return someVariable.variableName;
}
getNameOfVariable(myVariables[variableName]);
Obviously, this amounts to a lot more work than just using the variableName variable directly, but it could be necessary in some more complicated situations.
See working with objects in JS reference

Dynamically assign name to object array [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 10 years ago.
I have a javascript issue.
If I have an object array objAr, the object consists of id,name.
If I was to access objAr[0].id it returns the id value of the first object. What would happen if the object is dynamic and therefore I do not know what it consists of, is there a way to dynamically call the Object attribute?
Currently I am creating another array
var theArr = new Array("id", "name");
and call:
objAr[0].theArr[0] instead of objAr[0].id.
Is there a way to do this better using Javascript?
With Javascript you can call all of the attributes in an object without knowing the keys.
See below:
for(key in objAr[0]) {
console.log(objAr[0][key]);
}
If you just wanted the first attribute you could run:
for(key in objAr[0]) {
var attFirst = objAr[0][key];
break;
}
Additionally for the JS array you could have used square brackets.
var theArr = ["id", "name"];
hope that helps
In javascript you can always use the "array notation" in place of the "dot notation"
So these 2 lines are the same
objAr[0].id
objAr[0]["id"]

Categories

Resources