I have the code shown below.
My problem is: the part console.log(obj) is saying that Object {InternalNumber = 22 } and leaving out all the other variables.
I am expecting it to say:
Object { Id = someID, ParameterId="someParaId", InternalNumber = someNr, value="someValue"}
What might be wrong?
If you haven't noticed... I am saving the object to localStorage, and then retrieving it from there.
function getModel() {
var model = {
Id: '',
ParameterId: '',
InternalNumber: '',
Value: ''
}
return model;
}
function saveObjectToLocal() {
model = getModel();
model.Id = $(this).find(':input[name$=Id]').val();
model.ParameterId = $(this).attr('id');
model.InternalNumber = currentParcel.children('#viewModel_InternalNumber').val();
model.Value = $(this).find(':input[name$=Value]').val();
localStorage.setItem("model", JSON.stringify(model));
}
function getObjectFromLocalAndInsertInFields() {
obj = JSON.parse(localStorage.getItem("model"));
console.log(obj);
}
How are you calling saveObjectToLocal function. $(this) inside of that function is probably not matching anything because "this" is probably the global (window) object, and DOM elements aren't matched within the window object.
To see what I'm talking about. Run:
$(this);
$(this).find("input");
$(this).find("input").attr("id");
from your console. The first output will be length 1 of just window, the second would be an empty jQuery object, and the third would be undefined.
Calling .val() and .attr on an empty jQuery list would be undefined and therefore not serialized to JSON. InternalNumber is serialized because currentParcel.children is giving a match. You need to fix the $(this) selectors.
Json stringify function will exclude attributes with undefined value, so check first if the missing attributes have values
Related
The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name
I am trying this to get input as an argument with some objects,
function write(param) {
var str = param.str;
var elem = param.elem;
document.getElementById(elem).innerHTML= str;
}
and I'm passing this as an argument,
write({
elem:"op",
str:"Hello"
});
The thing I have to do is that I am having font tag with id 'op',
<font id="op"></font>
and when I run this I wont print Hello, as I have given Hello as an object parameter with op element for output.
I'm not sure where exactly your code has gone wrong. Here you can see that both the javascript and the html you produced should work together just fine.
function write(param) {
var str = param.str;
var elem = param.elem;
document.getElementById(elem).innerHTML = str;
}
write({
elem: 'op',
str: 'Hello'
})
<font id="op"></font>
As far as I'm seeing it, your code works as intended.
Answer for using an options object on a function:
In ES6 default parameters can prevent values to be undefined, however it does not actually compensate for the case that you're passing an object with missing parameters.
In this case I would suggest using Object.assign():
function write(options){
options = Object.assign({}, {
myDefaultParam: 'Hello',
elem: null,
str: ''
}, options);
if(options.elem) document.getElementById(options.elem).innerHTML = options.str;
}
What Object.assign() does is to merge a object of default options with the provided functions, allowing you to set default parameters that you can rely on. In this case write({}) would result in options being this object:
{
myDefaultParam: 'Hello',
elem: null,
str: ''
}
If this is overkill for you, I would suggest to simply check wether the keys are defined on your param object like this:
function write(param){
if(!param || !param.elem || !param.str) return false;
return document.getElementById(param.elem).innerHTML = param.str;
}
Object :
var userData = {
"a1":{"a":"1"},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
I need to delete Object with key "a1" and place a new object i.e. "f6" at same place.
i.e.
userData["f6"] = userData["a1"];
userData["f6"].new = "true";
delete userData["a1"];
Output:
userData = {
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
"f6":{"a":"1", new:true},
};
Expected O/p:
var userData = {
"f6":{"a":"1", new:true},
"b2":{"b":"2"},
"c3":{"c":"3"},
"d4":{"d":"4"},
"e5":{"e":"5"},
};
Thanks in Advance..
In Javascript, objects have no specific order for their properties. When you see them as a JSON, the properties are shown in the same order they where declared or added. To mantain a specific order, you may do changes in your object and implement an Array.
in linking javascript objects with html objects
// javascript element
var element = { tag:'input', name: 'email', value:null, dom: null,
verifyFunc: function() {...}, postFunc: function() {...},
rcdElement: some_element }
// lookup javascript element from dom
var doms = {};
// create html element for dom
var item = document.createElement(element.tag);
item.name = element.name;
...
// cross-link
doms[item] = element;
element.dom = item;
// using it in generic "onchange" trigger
function changeTrigger(e) {
var el = doms[e.target];
....
};
are there any dangers lurking in this approach?
Object keys are strings. So, when you try to use a DOM object as an object key, it will call toString() on the DOM object and use that as the key. toString() on DOM objects returns non-unique things like this:
[object HTMLParagraphElement]
So, it won't cause an error, but it probably won't do what you want. It would probably make more sense to use the object's ID as the key and generate a unique ID to put on the object if the object doesn't already have an id.
As best I can tell, any use of using an object as a key can also be done with the id as a key.
When I run this in Firefox 10:
window.onload = function(){
var doms = {},
item,
element = {
tag: 'input',
name: 'email',
value: null,
dom: null
};
for (var i = 0; i < 10; i++) {
item = document.createElement(element.tag);
item.name = element.name + i;
document.body.appendChild(item);
doms[item] = element;
}
console.log(doms);
};
I see the following in Firebug's console:
Object { [object HTMLInputElement]={...}}
Which expands to:
[object HTMLInputElement] Object { tag="input", name="email", value=null, more...}
dom null
name "email"
tag "input"
value null
http://jsbin.com/efuluk/
Note, there's only one reference/object pair, not ten. I suspect you can't do this, and I would advise against it anyways (in lieu of a specific citation supporting my hunch).
when executing the following code firebug tells me: values[this.geo.value] is undefined
what is the problem?
$.get('./RDFexamples/tin00089_test2.rdf', null, function (rdfXml) {
var rdf, json = {};
var values = new Array();
rdf = $.rdf()
.load(rdfXml)
.prefix('', 'http://ontologycentral.com/2009/01/eurostat/ns#')
.prefix('qb', 'http://purl.org/linked-data/cube#')
.prefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
.prefix('dcterms', 'http://purl.org/dc/terms/')
.prefix('sdmx-measure', 'http://purl.org/linked-data/sdmx/2009/measure#')
.where('?observation a qb:Observation')
.where('?observation dcterms:date ?date')
.where('?observation sdmx-measure:obsValue ?measure')
.where('?observation :geo ?geo')
.each(function () {
values[this.geo.value].push(this.measure.value);
//alert(this.date.value)
//alert(this.measure.value)
//alert(this.geo.value)
}
);
alert(values);
});
values[this.geo.value] is never initialized so you can't do .push because values[this.geo.value] is undefined, you first need to create an array in values[this.geo.value] before you can push things into it.
Pseudo-code example
if values[this.geo.value] == undefined {
values[this.geo.value] = []
}
values[this.geo.value].push(...)
push is a method of the Array object itself - you are calling it on a value within the Array (which has probably not been set, hence 'undefined'). It's unclear what this.geo.value is, but assuming its the index of the array item you are trying to set, your options are:
values.push(this.measure.value);
or
values[this.geo.value] = this.measure.value;