I'm very new to JavaScript. I was trying pushing new values to an object. But when I tried to push an array that doesn't exist in myObj, I got Cannot read property 'push' of undefined error.
My code is below:
var myObj = {
first: "first value",
second: "second value",
}
myObj.third.push(123)
console.log(myObj)
But when I check if it doesn't exist and create an empty array, then push it, it works. =>
var myObj = {
first: "first value",
second: "second value",
}
myObj['third'] = myObj.third || []
myObj.third.push(123)
console.log(myObj)
I wonder if bottom code is best practice and if there is a better way to do it.
The push method is part of the Array prototype in your particular case you are trying to access a not defined property which in JavaScript is consider undefined so you are trying to do transalates into something like:
myObj.third.push => myObj.undefined.push
Because myObj does not have a third key you can try this in the console doing console.log(myObje.third );
So the engine returns an error saying that undefined does not have a property push that is only available in Array.
In this case you need to set assign a value to myObj.third before using it as an array, for that there are multiple ways to set the value as an array your answer above is one of those ways:
myObj['third'] = myObj.third || []
That line works however if for example myObj.third has a value will use that as a value as you are assigning the result of the operation myObj.third || [] which in this scenario anything that evaluates as truthy will be returned if for instance you have:
myObj.third = true;
And then you do:
myObj.third.push(123);
An error will be displayed Uncaught TypeError: myObj.third.push is not a function as currently myObj.third is not an array.
So you need to make sure you are operating over an Array when using push, or at least when you initialize the value of your property is set as an Array, you can find more details on Array construction on this page.
Alternatives you can do to check before pushing are:
if ( ! Array.isArray(myObj.third) ) {
myObj.third = [];
}
myObj.third.push(123)
Updated 2nd:
You could do a ternary operator
let myObj = {
first: 'first value',
second: 'second value'
};
myObj.third = myObj.third ? [...myObj.third, 123] : [123];
console.log(myObj);
I have a form, that I need to get the values from:
var formConfig = JSON.stringify($("#bookingform").serializeArray());
which returns below:
[{"name":"client_id","value":"1"},{"name":"consignee_id","value":""},{"name":"client","value":"DAKO"},{"name":"model","value":"2"},{"name":"type","value":"2"},{"name":"temperatur","value":"2"},{"name":"shipper_labels","value":"1"},{"name":"batteri_labels","value":"1"},{"name":"batteri_number","value":"2222"},{"name":"pickup","value":"April 27, 2017 18:25"},{"name":"intern_marks","value":"fdsfads"},{"name":"extern_marks","value":"sadsfdsf"},{"name":"consignee","value":""},{"name":"marks","value":""}]
I then need to access above values from the JSON string, which I am using this function to:
var confirmBooking = function(element, setting, correct, notcorrect) {
$('.confirm-booking')
.find(element)
.html(setting === 1 ? correct : notcorrect);
};
The thought is, I can use above function:
confirmBooking('.config_batteri', formConfig.client_id, "Yes", "No");
and so on..
formConfig.client_id should return 1, since that's the value in the JSON string above.
However it returns undefined:
console.log(formConfig.client_id); // Returns "undefined"
You need to use JSON.parse(), to make it a regular JavaScript object again.
What JSON.stringify() does is, as the name implies, make it a string. That is just a regular string, that represents JSON data. It doesn't magically have the JSON data properties.
Furthermore serializeArray() returns an array of {name: ..., value: ...} objects. If you didn't turn it into a JSON string, the result still could not easily be accessed by doing formConfig.client_id. You'd have to loop through the formConfig array, to find the desired name/value pair.
From the looks of it, you don't need to turn the JavaScript object into JSON at all, if you are just going to use it in the same script (unless you are going to send the JSON string somewhere else perhaps).
Based on OP's comments, I'm assuming OP just want to access a particular form element's value. Using jQuery, this can easily be accomplished with:
// get the value of the client_id element (assuming it's an input element)
var client_id = $( '#bookingform input[name="client_id"]' ).val();
// call the function
confirmBooking( '.config_batteri', client_id, "Yes", "No" );
If you want to have an object with all the form values, have a look at the answers in this question.
Do this:
var jsonStr = '[{"name":"client_id","value":"1"},
{"name":"consignee_id","value":""},
{"name":"client","value":"DAKO"},
{"name":"model","value":"2"},
{"name":"type","value":"2"},
{"name":"temperatur","value":"2"},
{"name":"shipper_labels","value":"1"},
{"name":"batteri_labels","value":"1"},
{"name":"batteri_number","value":"2222"},
{"name":"pickup","value":"April 27, 2017 18:25"},
{"name":"intern_marks","value":"fdsfads"},
{"name":"extern_marks","value":"sadsfdsf"},
{"name":"consignee","value":""},
{"name":"marks","value":""}]';
var obj = JSON.parse(jsonStr);
var val = obj[0].value;
The reason you can't do obj[0].name is because your parsed JSON object has a collection of objects, where the first object has this structure:
{
name:"client_id",
value:"1"
}
So, you have to access it using obj[0].value NOT obj[0].name as it would give you client_id.
I think that's what you want.
console.log(formConfig.confirmBooking);
would change of syntax help? please try
console.log(formConfig[0]['client_id']);
I hope it works for you
Since it's an array of objects, you target the first element which returns an object and then use the "value" property to get the actual value of 1 which you expected .
Also use parseInt("1") to get 1 as a type "number"
Hope this solves the issue ! Let me no ASAP
== EDIT
var formConfig = [{
"name": "client_id",
"value": "1"
}, {
"name": "consignee_id",
"value": ""
}, {
"name": "client",
"value": "DAKO"
}];
// This function returns the value for the name
function search(str) {
for (var obj of formConfig) {
if (obj.name == str) {
return obj.value;
}
}
}
search("client_id"); // 1
search("client"); // DAKO
Lets say I have the following object:
name = {
name_one : {
name_one_A : {
name_one_A_a : 'John',
name_one_A_b : 'Kate'
}
}
};
I could create a reference to 'John' by doing:
current_name = name.name_one.name_one_A.name_one_A_a;
Lets say I'm referencing "name.name_one.name_one_A" several times, is there a way to create a referencing to this nesting? This doesn't work, but something like:
A = name.name_one.name_one_A;
name = A.name_one_A_b;
'name' would then equal 'Kate'. I know this doesn't work like that, but I'm just wondering if there is a way to accomplish this?
Thanks for any help!
It's a bit hard to tell exactly what you're asking which has caused some confusion among the answers.
If you're referencing name.name_one.name_one_A multiple times, you can save that once and then use it:
var x = name.name_one.name_one_A;
x.name_one_A_a = 'Bill';
x.name_one_A_b = 'Sue';
This works ONLY because the value of name.name_one.name_one_A is an object (Object, Array or Function). So, when you save it to another variable, you aren't actually saving a reference to name.name_one.name_one_A, but rather getting the value of that property which is itself an object. And, when you then modify that object, since name.name_one.name_one_A also points to that same object, you will see the value change there too.
Javascript does not have the ability to create a reference to a particular property on an object such that you could use only that reference to then change the value of that property.
Using C/C++ terminology, you can't create a pointer to a property on an object in Javascript such that you could change the value in that property using only that pointer.
You would instead have to pass the host object and the property name and you could then change the value of the property on that host object.
Or, if the value of the property was itself an object (Object, Array or Function), then you can get the value of the property and then change the object that it points to.
So, in your data structure:
var name = {
name_one : {
name_one_A : {
name_one_A_a : 'John',
name_one_A_b : 'Kate'
}
}
};
There's no way to get a direct reference to:
name.name_one.name_one_A.name_one_A_a
that would let you modify just the contents of that property at some later time. Instead, you'd have do something like this where you get a reference to the containing object and use that:
var obj = name.name_one.name_one_A;
var prop = "name_one_A_a";
// and then some time later:
obj[prop] = 'Bob';
// or
obj.name_one_A_a = 'Bob';
Firefox Scratchpad had an issue with a variable named "name", but this works:
var foo = {
'name_one' : {
'name_one_A' : {
'name_one_A_a' : 'John',
'name_one_A_b' : 'Kate'
}
}
};
var A = foo.name_one.name_one_A;
console.log(A.name_one_A_b);
//yields
Kate
Update:
You can get a reference that is able to change a property value:
var foo = {
'name_one' : {
'name_one_A' : {
'name_one_A_a' : 'John',
'name_one_A_b' : 'Kate'
}
}
};
var A = foo.name_one.name_one_A;
console.log(A.name_one_A_b);
A.name_one_A_b = "bob";
console.log(A.name_one_A_b);
console.log(JSON.stringify(foo));
Yields:
"Kate"
"bob"
"{"name_one":{"name_one_A":{"name_one_A_a":"John","name_one_A_b":"bob"}}}"
So I have an array called xyz containing keys a and b.
I want to input these into another array as follows :
seats =[{
name : xyz.a.
address: xyz.b}];
however the xyz.a is being stored as an object and not by it's value in seats.name and prints undefined when i use console.log
I want to store xyz.a by its value such that seats.name gives the value stored in xyz.a
Javascript doesn't have variable references or aliases. When you assign a variable to another variable or object, it gets its value at the time of the assignment, it doesn't keep a link to the original location.
If you want something that always gets the current value of a variable, you have to use a function:
seats = [ {
name: function() { return xyz.a; },
address: function() { return xyz.b; }
}];
Then you would call the function to get what you want:
seats[0].name();
Assuming xyz is an object like
var xyz = {
a: 'foo',
b: 'bar'
};
Then, you can use
var seats = {
name: xyz.a,
address: xyz.b
};
I was trying the following code :
function doSomething(field, value) {
var someObj = { field : value };
console.log("The object looks like : %j, someObj);
}
I call it like doSomething('emailid', 'a#b.com');
The output was {field : 'a#b.com'}.
How can i make field to take the value from the function call?
Would like to get these values : {'emailid', 'a#b.com'}
Thanks for your time.
When you define an object with the object literal syntax you can either speciy the name of the key as you did, like {field: value} or you can use string literals to define the key such as {"field": value}. Unfortunately there is no way to substitute a variable for a key with object literal syntax, but there is a way to accomplish your outcome.
function doSomething(key, value) {
var someObj = {};
someObj[key.toString()] = value;
return someObj;
}
That should perform your task.