Pass object and properties by reference in Javascript - javascript

I've seen lots of questions about passing objects by reference in Javascript, but not the object and properties by reference. Is it possible?
Right now I only found a way to do it by going through some type of logic like this, which is terribly inconvenient:
let multipliers = {
none:1,
sin:2,
cos:3,
tan:4,
atan:5,
}
incMultiplier(shapesMovements[index], "rotation", "x", "sin")
function incMultiplier(shapeMovement, kind, dimension, multiplier){
var numOfKeys = Object.keys(multipliers).length;
if(kind === "rotation"){
if(dimension === "x"){
if(multiplier === "sin"){
if(shapeMovement.rotation.x.multiplier !== numOfKeys){
shapeMovement.rotation.x.multiplier += 1
}else{
shapeMovement.rotation.x.multiplier = 1
}
}
}
}
}
I'd just like to increase the property value by one with whatever object and property I've thrown into that function.
I've seen another post where you can pass parameters, but this looks to assemble a new object, and is not by reference. I need to actually edit the values on the object's properties.
Originally, this is what I was trying, and it did not seem to alter the object on a global level. Only locally to the function:
incMultiplier(shapesMovements[index].rotation.x.multiplier)
function incMultiplier(multiplier){
var numOfKeys = Object.keys(multipliers).length;
if(multiplier !== numOfKeys){
multiplier = multiplier + 1
}else{
multiplier = 1
}
// always results in the same number.
// Does not keep increasing every time the function is called.
console.log(multiplier);
}

Originally, this is what I was trying
You're not passing an object with its properties there. You're passing the value of a single property, and assignments to multiplier do indeed just overwrite the local variable in the function. You need to pass an object and explicitly assign to its property:
function incMultiplier(valueObj) {
var numOfKeys = Object.keys(multipliers).length;
if (valueObj.multiplier !== numOfKeys) {
valueObj.multiplier++;
} else {
valueObj.multiplier = 1
}
}
incMultiplier(shapesMovements[index].rotation.x)
incMultiplier(shapesMovements[index].position.x)
incMultiplier(shapesMovements[index].rotation.y)
incMultiplier(shapesMovements[index].rotation.z)
It's not necessary to pass the whole shapesMovements objects and everything nested within them, passing a single mutable object is enough.

Related

How to have an object key depend on another key in the same object?

I have a very simple function that builds an object and logs it.
One of the keys in the object should be depending on another key.
I think it would be much clearer when I add the code
module.exports = function (information) {
var numObj = {
[-1]: "accepted",
[0]: "fail",
[1]: "success"
}
console.log(numObj)
var ip = require('ip');
var logObj = {
UUID: information.UUID, // get from outside
FN_TIME_STAMP: information.FN_TIME_STAMP, // not sure if necessary
FN_CORRELATION_ID: information.FN_CORRELATION_ID,// get from outside
FN_REF_ID: information.FN_REF_ID, //get from outside
FN_METHOD_NAME: "docToMail", // constant
FN_STATUS_CODE: information.FN_STATUS_CODE, //get from outside
FN_STATUS_DESC: numObj[this.FN_STATUS_CODE], // depends on FN_STATUS_CODE
FN_DOC_ID: information.FN_DOC_ID, //get from outside
FN_USER_NAME: "", // empty for now, probably un-necessary
FN_APP_ID: information.FN_APP_ID, //get from outside
FN_RMT_ADDRS: ip.address(),//ip address of local machine
FN_NUM_OF_RETRIES: information.FN_NUM_OF_RETRIES, // get from outside
FN_FILETYPE: information.FN_FILETYPE, // get from outside
FN_REC_STATE: numObj[this.FN_STATUS_CODE] //depends on FN_STATUS_CODE
}
console.log(logObj)
}
I just want FN_REC_STATE and FN_STATUS_DESC to be a string depending on FN_STATUS CODE.
If its -1 i want the string to be "accepted"
If its 0 i want the string to be "fail"
If its 1 i want the string to be "success"
as it as right now i just get undefined, please help!
Thanks
Assuming that information.FN_STATUS_CODE is either -1, 0 or 1, the following solution should work.
If you change
FN_REC_STATE: numObj[this.FN_STATUS_CODE]
to
FN_REC_STATE: numObj[information.FN_STATUS_CODE]
then it should put the correct value into FN_REC_STATE.
This is because by the time that faulty line is evaluated, this.FN_STATUS_CODE hasn't been defined.
You should also change this for the definition of FN_STATUS_DESC.
Also, it looks like you may be misunderstanding what this refers to in the context of that function. It actually refers to the global object, rather than the logObj object.

Adding meta data to a primitive in javascript

Background
We have much of our data formatted like
var X = {value:'some val',error:'maybe an error',valid:true}
as a result we find ourselves calling X.value ALL the time.
We don't use the .error or .valid nearly as much, but we do use it.
What I want
To quit calling .value everywhere, but to still have access to meta data on a per data point level.
The Question
Is there one of
A) A way to put meta data on a primitive? attaching .error to an int for example? Is it possible for bools or strings?
B) A way to make a class that can be treated as a primitive, providing a specific data member when I do? IE X.value = 5, X+3 returns 8.
C) A better design for our data? Did we just lay this out wrong somehow?
You can set the method toString() to your object and return value.
var X = {
value: 1,
error:'maybe an error',
valid:true,
toString: function() {
return this.value;
}
}
X.value = 5;
console.log(X+3);
You can represent you data as a function object that also has properties:
var X = () => 1;
X.value = 1;
X.error = 'maybe an error';
X.valid = true,
console.log(X()); // 1
console.log(X.valid); // true
For better design you can encapsulate the creation of the data object in another function.

Changing the JSON key and keeping its index same

I want to change the key of JSON attribute and keep/persist its position/Index.
E.g.
{"Test1" : {
mytest1:34,
mytest2:56,
mytest6:58,
mytest5:89,
}
}
Now I want to change the key mytest6 to mytest4 and keep its position as it is.
Note: In my case I can't use Array.
Thanks.
jsonObj = {"Test1" : {
mytest1:34,
mytest2:56,
mytest6:58,
mytest5:89,
}
};
var old_key = "mytest6";
var new_key = "mytest4";
if (old_key !== new_key) {
Object.defineProperty(jsonObj.Test1, new_key,
Object.getOwnPropertyDescriptor(jsonObj.Test1, old_key));
delete jsonObj.Test1[old_key];
}
console.log(jsonObj);
This method ensures that the renamed property behaves identically to the original one.
Also, it seems to me that the possibility to wrap this into a function/method and put it into Object.prototype is irrelevant regarding your question.
Fiddle

How can I compare a string to an object key and get that key's value?

I want to do something relatively simple, I think anyways.
I need to compare the pathname of page with an object's kv pairs. For example:
if("pathname" === "key"){return value;}
That's pretty much it. I'm not sure how to do it in either regular Javascript or jQuery. Either are acceptable.
You can see my fiddle here: http://jsfiddle.net/lz430/2rhds1x3/
JavaScript:
var pageID = "/electrical-electronic-tape/c/864";
var pageList = [{
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
}];
var label = pageID in pageList;
$('.el').html(label);
First, your "pageList" should just be a plain object, not an object in an array:
var pageList = {
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
};
Then you can set "label" to the value from the mapping:
var label = pageList[pageID] || "(not found)";
That last bit of the statement above will set the label to "(not found)" if the lookup fails, which may or may not be applicable to your situation.
It depends kinda on the logic you want to implement. If you want to say "if object has the key, then do X, and if not, then do Y", then you handle that differently than "set label to the object's key's value if the key is there, or else set it to undefined or something else".
For the first case you do:
if (pageList.hasOwnProperty(pageID) ) {
label = pageList[pageID];
}
else {
// do whatever, maybe some error?
}
For the second case, you can just say
var label = pageList[pageID] || 'notFound';
As indicated by #Pointy, either get rid of the array or subsiture pageList[0] for pageList and pageList[0][pageID] for pageList[pageID] above, if you need to keep the array.

Add another value to nested javascript object?

I have the following JavaScript object, with a property called rates, which contains another object with the actual rates. Now I want to add a new rate "CAD":0.972254 to the rates. How can I add this one value to the list?
var Currency = {
rates: {"USD":1.0,"EUR":1.3497,"GBP":1.60403},
convert: function(amount, from, to) {
return (amount * this.rates[from]) / this.rates[to];
}
};
You can do it either way
Currency['rates']['CAD'] = 0.972254;
Or,
Currency.rates.CAD = 0.972254
Fiddle Here
You can assign a new property to existing object like:
Currency.rates.CAD = 0.972254
Currency.rates.CAD = 0.972254;

Categories

Resources