How to add a property to an object using the ['key'] notation? - javascript

JavaScript documentations states that in order to add a property to an existing object you could do the following.
data["property"] = value;
or
data.property = value;
In my case, I'm trying to convert my model ID (received by the server) to string before adding it, such as:
data.model[id.toString()] = false;
But I get the following error:
Uncaught TypeError: Cannot set property '1' of undefined
I initially though that it was because you couldn't use an alphanumeric string or some kind of weird limitation, so I tried prefixing my ID with a letter, such as:
var id = 'k' + id.toString();
Still doesn't work! But when I use Chrome's Console panel and do it manually, such as:
var data = {};
var data['1'] = false;
That works, so what am I doing wrong?
What is the official name for data.['key'] = value; operations anyway? It would help knowing when trying to Google for help.
Update 1: Ok, it seems that it may be due to the following:
var data = localStorage.getItem('model.state');
When I change it to:
var data = {};
It suddenly started to work!
Update 2: I see what I'm doing wrong (but still not sure why it was giving me an 'undefined' error... anyone?).
I did the following:
var data = localStorage.getItem('model.state');
if (data) data = JSON.parse(data);
And it started to work as expected. Sorry about that... thanks for the help everyone!

You get this error because data.model is not defined. In order to prevent the thrown error you can use:
data.model = data.model || {};
data.model[id.toString()] = false;
This is the short version of:
if (!data.model) {
data.model = {};
}
data.model[id.toString()] = false;

Related

Replacing JQuery .val() with JS .value

I'm going through some legacy code on a submission form and replacing JQuery w/ vanilla JS.
Right now, I have this function that uses .val() (JQuery) to grab the value for an undefined input:
myFunction: function(){
var subscription = $('input[name="subscription_id"]').val();
// Do something with subscription
}
When I run the code in my browser, I get no issues - the code is meant to work only if a subscription is passed into the input - if it's not there, we just get an undefined value. The value returned by the JQuery combo of $() and .val() console logs to 'undefined'.
When I replace the JQuery with vanilla JS, like so:
myFunction: function(){
var subscription = document.querySelector('input[name="subscription_id"]').value;
// Do something with subscription
}
And then try to run my form, I get the following error in the console:
Uncaught TypeError: Cannot read property 'value' of null
Why is this happening? And is there a workaround for this? Any help is appreciated. Thanks in advance.
This happens because
document.querySelector('input[name="subscription_id"]')
does not exist. For vanilla js, you need to check if it exists first, then get the value if it does. jQuery has a silent fail for this.
var element = document.querySelector('input[name="subscription_id"]');
// If it exists, return its value, or null
var subscription = element ? element.value : null;
Just use a condition:
var elem = document.querySelector('input[name="subscription_id"]');
var subscription = elem ? elem.value : "";

Uncaught TypeError: Cannot read property 'options' of undefined javascript

Everything works fine but from time to time there is a problem with the function. This makes it impossible to click a button and select a value from list. I tried to debug it but nothing is returned in the console.
_getSimpleProductId: function (element) {
var allOptions = element.config.options,
value = element.value,
config;
config = _.filter(allOptions, function (option) {
return option.id === value;
});
config = _.first(config);
return _.isEmpty(config) ?
undefined :
_.first(config.allowedProducts);
}
Error occurs:
Uncaught TypeError: Cannot read property 'options' of undefined
I think I have to change my question to "What I'm doing wrong?".
you should null check element.config
var allOptions = element.config ? element.config.options : null;
It looks like it's not always defined in your code
Your problem is that element.config is undefined.
You can either go with Basem's anwser (which would totally work) or find the source of the problem.
To me it looks like you expect to have options for the rest of your code, so I would go with the second solution.
Cheers!

how to get/set TestStep's property value using javascript in soapUI?

i have tried using Groovy script.
the following code is to set property value using roovy script:
testRunner.testCase.testSuite.testCases[testCaseName].testSteps[testStepName].setPropertyValue("request",object);
"request" is a property of testStep.
object is a some value.
when i try above code in javascript but i got following error:
org.mozilla.javascript.ecmaerror: TypeErro: org.mozilla.javascript.ecmaerror Cannot read property "testSteps" from undefined.
So please tell me how to use in using javascript?
hurra, i got solution. Please see following code:
var project = testRunner.getTestCase().getTestSuite().getProject();
var testSuite = project.getTestSuiteByName("TestSuite");
var testCasesItr=testSuite.getTestCaseList().iterator();
while(testCasesItr.hasNext())
{
var testStepsItr = testCasesItr.getTestStepList().iterator();
while(testStepsItr.hasNext()){
var testStep = testStepsItr.next();
log.info(testStep.getPropertyValue("response"));
// here you can set property
// testStep.setPropertyValue("request","someValue");
}
}
above code will run for all the testcases.

TypeError while trying to copy json data js

i'm new on javascript and also working with json. i'm trying to get some json data and store some of them in keepGetData. but when I want to get an entry, it says TypeError.
what is wrong with my code?
TypeError: undefined is not an object (evaluating 'keepGetData[j] =
result[i]')
thanks in advance
var keepGetData;
function getList(){
$.getJSON(url, function(result){
var j=0;
for(var i=0,len=result.length;i<len;i++){
if(result[i].parentId == 1 && result[i].restaurantId == restId.id[0]
{
keepGetData[j] = result[i];
j+=1;
}
}
});
You need to initialize your variable:
var keepGetData = [];
Please do use strict mode by writing "use strict" in the first line of your Javascript files. That catches the use of uninitialized variables much easier.
var keepGetData=[];
You should use above code.You need to define the variable as array.

Find keywords in a substring using javascript/jquery - I'm getting a type error in my code

I need to create a script that will filter out content based on a list of keywords (if the content contains one of these keywords, I want to apply a style to it).
So far, I have this code:
jQuery.expr[':'].mcontains = function(obj, index, meta, stack){
result = false;
theList = meta[3].split("','");
var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
for (x=0;x<theList.length;x++) {
if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
return true;
}
}
return false;
};
$("div:mcontains('facer','non')").css("background","red")
I did not write this myself, I found it online, but I got it working fine the way I need it in a fiddle:
http://jsfiddle.net/jtmVf/1/
However, when I try to port it into a project, I am getting this error in firebug:
TypeError: meta is undefined
On this line:
theList = meta[3].split("','");
I'm not sure why it's undefined there, but not throwing an error on the fiddle? There are no conflicts (I removed all other js except jquery.min in order to see if that was the issue).
I was hoping someone here would be able to see what I'm missing, what is wrong with this script?
post your code where you are assigning the "meta" array contents. Because these type of error usually shows when there is not such index in the array

Categories