JS object access - javascript

I have a js object and i'm trying to access it directly without having to do something like :
for(i in data) { obj = data[i] }
is there a better way to access this object without looping ? (i'll always have 1 result)
here is the firebug result for console.log(data) :

No, you can't access a property without knowing its name (aside from using fancy for-of-loops). And to get that name, you only can enumerate the properties with a for-in-loop or use Object.keys/….getOwnPropertyNames.
If you know that you always have exactly one key in your object, you might have chosen the wrong data structure.

Related

How can set a property using the same name without changing existing value

Using JavaScript, how can I set property of an object that already has property with the same name? For example, what i want to output is:
var obj = {
name: "foo"
};
obj[name] = "baz";
Normal output is:
console.log(obj) => {name:baz}.
I want to output:
console.log(obj) => {name:foo,name:baz}.
I know that is not the best practice, but is that possible?
You can read about core js concepts and also about basic data types in programming, like Maps and Arrays.
I can try to guess that your task is to store some similar data structures in array:
var list = [{name:'foo'},{name:'baz'}]
You simply can't do that. The latest value of the property will always override the previous one.
Even merging objects with same property names won't help you - shallow merge, or deep merge.
However, there are a few very weird cases with some JavaScript frameworks where this might happen - in Vue.js, for instance. But that misses the point since we're considering only plain Javascript.

Simple JS AutoMock Possible?

Im not really getting into the details of WHY doing this as its needed.
Supose i have a simple object.
var obj = {};
Lets say i want to access a random property of that object
obj.randomProp
This is getting me undefined.
Now, would it be possible, for that obj.randomProp return me another empty object ( {} ) ?
Of course, with no property declaration as obj.randomProp=123. I was thinking on this to be dynamic, somehow like a default property getter as if everytime you try to get a property of this element, you will get a new empty object for it.
Is this possible in JS ?

Javascript place object in object

Is it possible to store an Object into an Object..I have tried to this in my code with entry:entry but no success.
I have no problem with Object[String, String] but Object[Object, String] is not working for me.
$.each(data.scheduleEntries, function(index, entry){
arr[{entry:entry}] = entry.startDate;
})
No, it is not possible to use objects as keys in objects. Property names always are strings. You can use objects as property values of course.
In your case, using arr[entry] directly should work; if you really need objects as keys you will be able to use Map objects with ES6 (there also exist less efficient shims).

JSON get value of a param of a object whose object name is random

I am very new to JSON, have been pestered to get this done.I have to get the value of "extract" as in the given diagram. This diagram is a object diagram of a json. The value 21721040 can be random, thus I do not know the name of the object whose one of the members I seek.
Thus I cannot do something like
query.pages.21721040.extract
So how can I get the value of "extract"?
Out of curiosity should the object whose name is a numeral create an error when I try to access one of its members? Or they just work? For example in this case one of the object's name is "-1".
If I try to access the value "url" after parsing in JS like this:
query.pages.-1.imageinfo.0.url
Will it throw an error?
try this :
query.pages[Object.keys(query.pages)[0]].extract
try query.pages["-1"].imageinfo[0].url.
actually all the fields can be considered as string. so you can write query["pages"]["-1"]["imageinfo"]["0"]["url"]
if you do not know the key, use Object.keys() to find out the keys associated to that object. this key can be any key belong to the object or the object it has been inherited from. to find out only the object's own key user hasOwnProperty
If you don't know the property name, you can iterate over the properties on the object yourself:
for (var key in query.pages) {
if (query.pages.hasOwnProperty(key)) {
console.log(query.pages[key].extract);
}
}
Alternatively, you can use the relatively modern Object.keys() to obtain an array of keys that the object has.

referencing JS object member without the key

var foo = { "bar": {"blah": 9 } };
Is there a way to get the ["blah"] value of the only member of foo if I don't know the key is "bar"?
Can I somehow reference the first member of an object without knowing its key?
I'm looking for the equivalent of
foo[0]["blah"] if foo were a normal array.
In my case, I can't practically iterate on foo to get the key.
Is that clear?
As far as I know, with a Javascript Object (in the literal sense, the object of type `Object) the only way to do this is:
for(var i in foo) {
var value = foo[i].blah;
break;
}
Now value will contain the value of the first enumerable property of the bar object in the foo object. You could, of course, abstract this into a function. I was going to write an example, but CMS has a fantastic one in his answer here.
Edit: Agree with #kangax, it's much more safe to make a normal function, without polluting the native Object.prototype, which can lead to unexpected behaviors:
function firstMember (obj) {
for(var i in obj)
if (obj.hasOwnProperty(i)){ // exclude properties from the prototype
return obj[i];
}
}
firstMember(foo)['blah']; // 9
Objects in Javascript are unordered collection of name/value pairs, so there's really no such thing as accessing first or last property of an object. The only way to find certain key's value is to iterate over an object (with for-in). You can stop on the first iteration, but an order is not specified, so two different implementations can return two different keys on a first iteration.
I'm afraid what you're attempting to do is just not possible. Objects are essentially hash maps, so the order in which properties are stored should appear at a random location in the object's memory (And the better the hash function, the more random the locations).
You can see this for yourself if you step through a loop that iterates over all the properties of an object. There is no set order in which to iterate through because of the random nature of the structure.
Perhaps you could store the values in both an object and an array?
Just have a look here:
http://dean.edwards.name/weblog/2006/07/enum/
how they iterate through the object without knowing its structure.

Categories

Resources