How do I set a JavaScript object's value to null - javascript

I have created this JS object from an array.
var rv = {};
$( ".part-name:visible" ).each(function( index ) {
//rv[$(this).text()] = arrayPartsName[$(this).text()];
rv[$(this).text()] = arrayPartsName[$(this).text()];
console.log(rv);
})
4GN: "4GN"
4GNTS: "4GNTS"
042645-00: "042645-00"
503711-03: "503711-03"
573699-05: "573699-05"
I have to use this object with Materialize Autocomplete and I have to edit it. The correct object must be, for example, like this
4GN: null
4GNTS: null
042645-00: null
503711-03: null
573699-05: null
How can do this?

Picking up from my comment. You can just set it to null ;) JavaScript is quite a cool language... you can pretty much set any object's properties to anything you want, null, a specific value, or even a function... see some more on the topic
But to focus on your specific question:
Change this line
rv[$(this).text()] = arrayPartsName[$(this).text()];
to
rv[$(this).text()] = null;
Something to be aware of
If you have property or key values in the JSON object with a dash in the name, you have to wrap it in quotes ", otherwise it wont be seen as valid. Although this might not be as evident, or an issue in your example as your keys are being added via the following function $(this).text().
var fruit = {
"pear": null, // something null
"talk": function() { console.log('WOOHOO!'); } // function
}
var apple = "app-le";
fruit[apple.toString()] = 'with a dash';
fruit["bana-na"] = 'with a dash';
// below is not allowed, the values will be evaluated as
// properties that dont exist, and then your js will fail
// fruit[pe-ar] = 'with a dash';
fruit.talk();
console.log(fruit);

Related

Add an object to JSON

I have a settings.json file that contains following data (where 123456789 is a distinct user id):
{
"123456789":
{"button_mode":true}
}
So what I need to do is push a similar id: {button_mode: value} object to this JSON file in case there's no entry for current user's id. I tried to use lcSettings.push() but obviously it did not work since I have an object, not an array. When I put square brackets instead of curly ones to make it an array, my code doesn't do anything at all.
Here's a snippet of it (Node.js):
var lcSettings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
var currentUser = id;
if (lcSettings.hasOwnProperty(currentUser)) {
// in case settings.json contains current user's id check for button_mode state
if (lcSettings[currentUser].button_mode == true) {
// if button_mode is on
} else
if (lcSettings[currentUser].button_mode == false) {
// if button_mode is off
}
} else {
// in case there's no entry for current user's id
// here's where I need to push the object for new user.
}
fs.writeFileSync('./settings.json', JSON.stringify(lcSettings))
Does anybody have ideas on how it can be implemented? Any help appreciated.
You can use bracket notation to add a dynamic property to an object:
lcSettings[id] = { button_mode: false };
You may also want to verify that settings.json is not empty otherwise the JSON.parse() will fail. In this case, you would want to initialize lcSettings to an empty object (lcSettings = {}) so the above will work.
To 'push' elements to an object you simply define them, as in
object['123456789'] = { button_mode: true };

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.

React-Native setState - both name and value from the same variable

Is it possible to enter only one argument to SetState that contains both the name and the value. See the example below. Is there something wrong with the brackets?
This would be handy when changing a lot of states at the same time. That is, first prepare them in one long string and execute setState only once. Thank you!
this.setState({myState: "help"}) // this works of course
whatstate='myState'
this.setState({[whatstate]: "me"}) // this too
whatstate2='myState: "please"'
this.setState(whatstate2) // but how to make this work?
// if you like to work only with strings
var whatstate = {};
whatstate['myState1'] = 'help';
whatstate['myState2'] = 'me';
whatstate['myState3'] = 'please';
// ^ this will produce an object equivalent to this
//whatstate = {
// myState1: 'help',
// myState2: 'me',
// myState3: 'please'
//}
// which you can use it to 'setState'
this.setState(whatstate);
You can call this.setState({ whatstate2 }) to achieve the same effect. This is the property value shorthand from ES6.
Reference: https://ariya.io/2013/02/es6-and-object-literal-property-value-shorthand
In case you'd like to update multiple states in one go, you can also do that like this.
this.setState({
myState1 : newState1,
myState2 : newState2
});
If the variable names are the same as the state names as mentioned previously, you can do.
this.setState({ myState1, myState2 });

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.

Javascript - Overriding property (not methods) inside an Object

Let us explain the question with an example. I have a text box. The textbox (every textbox) has a property called 'value'. I want to over ride that textbox.value and comeup with and
new thing. When the text in textbox is 'ranjan' then the textbox.VALUE property returns 'ranjan'. Now I want to thus overwrite this so that when you type textbox.VALUE you get a different thing say for example, RaNjAn or say, Mr. Ranjan or whatever.
We can over ride methods using Object.PROTOTYPE property. But how can we do it for non-function objects inside object for example the 'value' property in this case.
If i need to make the question more clear, please mention.
Regards - Ranjan.
You can define custom properties for your element using Object.defineProperty
If you have a case where you need to get the value of an element as Mr. <value> for example, then this approach will be useful. Overriding standard properties may not be such a good idea.
Demo: http://jsfiddle.net/zvCGw/2/
Code:
var foo = document.getElementById('foo');
Object.defineProperty(foo, "xvalue", {
get: function() {
return 'Mr. ' + foo.value;
},
set: function(_newValue) {
foo.value = _newValue;
}
});
foo.xvalue = 'Hello';
alert(foo.xvalue);
What you are trying to do is called type augmentation. In javscript there are types of things, such as the object type, array type, etc.
You can use the prototype to augment these built in types, for example, adding a new method that can be called on any object that is of the type array:
Array.prototype.myNewMethod = function() {
//the method logic
}
Then you can call your method on any array:
[0,1,2].myNewMethod();
There is no INPUT type in JavaScript, DOM elements are classed as Objects. But you could jerry-rig something together that kind of does what you need, like this
Object.prototype.changeValue = function(el) {
if (el.tagName === "INPUT") {
return "Mr " + el.value;
}
}
var testEl = document.getElementById("test");
document.write(testEl.changeValue(testEl))
Used in conjunction with this textbox:
<input id="test" value="Dan" />
You would then get the output 'Mr Dan'
However, this is not great, it's just to illustrate the point and is just something to get you started...
I made a fiddle so you can play around with it
You can redeclare value but it will do no good ;)
This example would do that if test is a textbox
var input = document.getElementById("test");
Object.defineProperty(input, "value", {
get : function () {
return "'" + this["value"] + "'";
},
set : function (val) {
this["value"] = val;
}
});
input.value = "Hello World";
alert(input.value);
Unfortunately, "this.value" will reference the getter causing infinite recursion.
Once redefined, the original value will no longer exist so you will have crippled the element object.
At least as far as I have been able to test.
If the property you're trying to override can also be represented by an HTML attribute (e.g. an input's value), then you can use getAttribute and setAttribute.
Object.defineProperty(myInputElement, 'value', {
get: function () {
return myInputElement.getAttribute('value');
},
set: function (value) {
myInputElement.setAttribute('value', value);
}
});
Note, however, that this override itself cannot be overridden without re-implementing it.

Categories

Resources