I have an object as follows:
{
"headerSection": {
"text": "Some Text",
"color": "red",
"fontSize": "12px",
"backgroundColor": "#000",
"textAlign": "left"
}
}
I have a dropdown list which users can choose a different font size ie 14px, 16px .. 20px
. On the change event of this dropdown I want to change the value of fontSize
in my above object so for that I do:
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj.fontSize = value;
console.log(JSON.stringify(headerObj));
});
In the above console.log
the output is:
{
"headerSection": {
"text": "Some Text",
"color": "red",
"fontSize": "12px",
"backgroundColor": "#000",
"textAlign": "left"
},
"fontSize": "20px",
}
Can someone please tell me what I am doing wrong.
You should update headerSection
fontSize property.
In your case the compiler looking after fontSize
property of your headerObj
object, it don't found it and create a new property for your object.
let headerObj={ "headerSection": { "text": "Some Text", "color": "red", "fontSize": "12px", "backgroundColor": "#000", "textAlign": "left" } } $('select').change(function () { var value = $(this).val(); headerObj.headerSection.fontSize = value; console.log(JSON.stringify(headerObj)); }).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="20px">20px</option> <option value="30px">30px</option> </select>
I believe, after looking at your output, that the fontSize
property is being improperly appended.
You need to do this to add it under headerSection
.
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj.headerSection.fontSize = value; // like this
console.log(JSON.stringify(headerObj));
});
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj.headerSection.fontSize = value;
console.log(JSON.stringify(headerObj));
});
you're adding a value to headerObj instead of headerObj.headerSection, as you can see from the console.log
You have a nested object. An unnested object would look like this
{
"text": "Some Text",
"color": "red",
"fontSize": "12px",
"backgroundColor": "#000",
"textAlign": "left"
}
Instead you have an outside object, with a property called "headerSection" pointing at another object. If you're not going to change your data structure, then you need to change your code to access the inner property. Something like this
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj["headerSection"]["fontSize"] = value;
console.log(JSON.stringify(headerObj));
});
Ok then you just need to make a little change.
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj.headerSection.fontSize = value; // See here.
console.log(JSON.stringify(headerObj));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.