I'd like to return the third node (hello3.com) of the key hello.com in javascript object.
nodes = {
"hello.com":
{
id:"hello1.com",
id2:"hello2.com",
id3:"hello3.com"
}
}
I know that I can fetch all the key/values like this:
newobject = nodes["hello.com"];
but how would I get the third. I'm aware that you can't count on the order in an object. If not, can I pull just the third by maybeb id3.
You answered your own question when you said that you can't count on the properties of an object to be in any certain order. If your properties are sequential in nature (your properties were counting up in your example), then I would suggest trying to use an Array.
nodes = {
"hello.com": [
"hello1.com",
"hello2.com",
"hello3.com"
]
};
In the above example, you would access the 3rd property with
nodes["hello.com"][2]
The double bracket notation is because "hello.com" is in quotes to allow a . in the name. If the key didn't require quotes, like helloCom as an example, you could use
nodes.helloCom[2]
Beyond this, if you name your keys sequentially, then you can impose an "order". It's not that any property is literally before or after another, but rather that you have informed yourself of what order YOU intend them to be.
You can try this,
nodes = {
"hello.com": {
id: "hello1.com",
id2: "hello2.com",
id3: "hello3.com"
}
}
console.log(nodes["hello.com"]["id3"]);
Use:
nodes['hello.com'].id3 or nodes['hello.com']['id3']
Both are corrent way to get id3 data from given object
BY INDEX :
About accessing by index, you can not achieve it directly. the closest you can get is array of keys but that also do not guarantee the order of keys returned. See this answer provided on other thread.
for (var i in nodes["hello.com"]) { console.log(i);//logs id,id2,id3 };
BY NODENAME:
nodes["hello.com"] returns object. You can use key to access the value by
1) using dot notation:
nodes["hello.com"].id3
2) or by bracket notation
nodes["hello.com"]["id3"]
Try one of the following expressions
nodes["hello.com"]["id3"]
or
nodes["hello.com"].id3
Related
I have an array of objects that is fed by an external API e.g
[{prop: val1}, {prop: val2}, {prop: val3}....]
I have to feed this object(my code) to a third-party library which expects the name of the property on the object to be 'xyz' instead of 'prop'.
What is the most efficient way (memory wise and faster) basically avoiding both:
1. iterating over the array
2. adding 'xyz' property to all objects in the array
to achieve this?
I am thinking along the lines of adding a getter for xyz to all objects that return the 'prop' value, but that does not save the looping.
Adding the getting on the prototype level (Object.property) seems like a bad idea at this point.
Edit: I am not looking for different ways to loop through arrays in javascript like forEach or map. I have a very specific ask, and i am interested in exploring if it is at all possible to simply have a property proxy for 'xyz'.
Array map is used to cycle trough an array.
myArray.map(function(obj){
obj.xyz = 'yourvalue';
return obj;
}
You can use Array.map to create a new from the array you received by the API.
var newArray = oldArray.map(function(obj){
return {newKey : obj.prop};
});
In this example, newKey will be the key property you want, instead of 'prop', and it's assigned the old 'prop' value
For example, if I have an object like:
{"angeredoutsidecontrol":"1","difficultiespileup":"2"}
And then later in a for loop I can access the key of angeredoutsidecontrol , how can I get the value returned as 0, which would represent which place in the object this key is?
There is no guaranteed order for keys of an object.
Definition of object from an old - but still effective in this case - documentation:
4.3.3 Object
An object is a member of the type Object. It is an unordered
collection of properties each of which contains a primitive value,
object, or function. A function stored in a property of an object is
called a method.
If order really matters to you, use array instead. For example:
[{ "angeredoutsidecontrol": "1" }
{ "difficultiespileup": "2" }];
The order of JSON objects is not maintained, so you can't do this.
[Is the order of elements in a JSON list maintained?
var myMoods = ["angeredoutsidecontrol","difficultiespileup"];
and
myMoods.indexOf( 'angeredoutsidecontrol' )
gives you position in your list
I am very new to JavaScript and I am trying to figure out how to set a function to remove the last key:value pair to the right, much like array.pop for an array. This is an assignment I am working on. It seems confusing to me because, from my limited understanding of JS their is no specific order in a list of properties in an object. If anyone has any insight I would appreciate it. Here is the object:
var array = {length:0, size:big, smell:strange};
this is where I have started to go, but just having a hard time completing the function:
array.pop = function() {
//...
};
Ultimately I would like it to turn out like this:
array = {length:0, size:big};
Thanks in advance.
Objects do not have any defined order of properties so there is no "last" property. You have to remove a property by name, not position.
You can, of course, iterate over the properties and inspect them as you iterate and decide whether you want to delete any given property by looking at its name. Some javascript implementations will preserve the order that properties were added, but that is specifically not guaranteed by the ECMAScript specification so it cannot be relied upon.
This will work
const car = {
color: 'blue',
brand: 'Ford'
}
let keys = Object.keys(car)
delete car[keys[keys.length-1]]
console.log(car)
This answer is good for those situtations where the key is dynamically generated numbers like 0,1,2,3,4 etc
const myObject = {
0: 'somestring',
1: 42,
2: false
};
delete myObject[`${Object.keys(myObject).length-1}`]
console.log(myObject);
output:
Object { 0: "somestring", 1: 42 }
this one line logic may not good when key is a string. So, carefully use it.
The snippet below demonstrates that "objects have no order", and an [inefficient] workaround: use an array alongside of the object, to store the order that the properties were added to the object.
Click to add random properties, and note the order that they appear below.
In CodePen (or on my webserver) the properties seem to be stored sorted numerically (even though they're stored as strings).
However, in the snippet below they seem to be ordered randomly.
Neither are the order that the properties are added.
It should be noted:
Unlike what common belief suggests (perhaps due to other programming languages like delete in C++), the delete operator has nothing to do with directly freeing memory. Memory management is done indirectly via breaking references.
More info: delete operator and Memory Management.
var obj={}, // object to store properties (keys) and values
props=[]; // array to store property names
add.onclick=function(){
var prop=rnd(), val=rnd(); // get 2 random numbers
obj[ prop ] = val; // add property & value → object
props.push( prop ); // add property name → array
updateInfo(); // display object
}
del.onclick=function(){
var lastProp=props.pop(); // get/remove last property name in array
delete obj[ lastProp ]; // remove property
updateInfo(); //display object
}
function rnd(){return Math.floor(Math.random()*1E5);} // random 0-99999
function updateInfo(){ // show pretty object 😘
info.innerHTML=JSON.stringify(obj).replace(/[\{\}]+/g,"").replaceAll(',','<br>');
}
<button id='add'>add new property</button>
<button id='del'>delete last added</button>
<div id='info'></div>
Doing so
var x = new Array();
x['length']=5;
will make x an array of 5 undefined items, but I actually want to have the value '5' stored at key 'length'.
Is that possible?
In javascript arrays do not have keys. You are looking for objects:
var x = {}
x.length = 5;
I have to parse a file containing many words and store the number of occurences of each word
Use an object, and make the words the keys. You aren't storing sequential / ordered data, so you shouldn't use an array.
var word_count = {};
for (var i; i < words.length; i++) {
var word = words[i];
if (word_count[word]) {
word_count[word]++;
} else {
word_count[word] = 1;
}
If you want to do this you'd be better off creating an object rather than an array. This should give you what you want.
var x = {};
x['length'] = 5;
You can call methods on a javascript object using two different syntaxes. The familiar 'dot' syntax with parens to invoke the method, and the square bracket syntax. You can 'call' a method on a javascript object using the syntax myObj["methodname"](args). This is handy when you want to construct the method name dynamically using strings. Remember, objects in javascript are very much like a hash table (dictionary) where keys denote property and function names. If a key's value holds a function, it can be invoked (using parentheses).
In your example, Array has a method called 'length'. You are inadvertently calling its setter (which sets the length of the array to empty values, i.e., undefined).
Putting that all aside, you really do want a hash (associative array) in this case. An array is an offset indexed data structure.
A simple object literal like myObj = {} will suffice to give you hash semantics (again, objects in javascript are already like hashes) and you can then call myObj.whatever = "some value"
You could use objects instead of arrays to store your data. But if you need to use Arrays (you might need to use their functionality), You could cripple the words and store them as array keys.
Use some kind of simple rule to follow to bypass all the possible keywords. For example prefix all your array keys with a "_" character. This way you could always restore the original words from the keys, by simply removing their first character, and you are sure you are not referencing any specific property of the Array objects (like the length property).
I have a js 'associative' array, with
array['serial_number'] = 'value'
serial_number and value are strings.
e.g. array['20910930923'] = '20101102'
I sorted it by value, works fine.
Let's say I get back the object 'sorted';
Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with
for (var i in sorted)
and just stop after ther first one...
thanks
edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).
2021 Update
Since ES6, properties with string keys are enumerated in insertion order. Here's a nice summary. My original answer from 2010 was correct at the time and is preserved below:
Original answer
JavaScript object properties are specified to have no order, much though many people wish it were different. If you need ordering, abandon any attempt to use an object and use an Array instead, either to store name-value objects:
var nameValues = [
{name: '20910930923', value: '20101102'},
{name: 'foo', value: 'bar'}
];
... or as an ordered list of property names to use with your existing object:
var obj = {
'20910930923': '20101102',
'foo': 'bar'
};
var orderedPropertyNames = ['20910930923', 'foo'];
Try this:
// Some assoc list
var offers = {'x':{..some object...}, 'jjj':{...some other object ...}};
// First element (see attribution below)
return offers[Object.keys(offers)[0]];
// Last element (thanks to discussion on finding last element in associative array :)
return offers[Object.keys(offers)[Object.keys(offers).length - 1]];
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object). The syntax is what makes it look like it does, but in reality it doesn't. So you have no "Order" to your objects.
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Javascript does not have, and does not
support Associative Arrays. However…
All arrays in Javascript are objects
and Javascript's object syntax gives a
basic emulation of an associative
Array. For this reason the example
code above will actually work. Be
warned that this is not a real array
and it has real pitfals if you try to
use it. The 'person' element in the
example becomes part of the Array
object's properties and methods, just
like .length, .sort(), .splice(), and
all the other built-in properties and
methods.
Just thinking off the top of my head, but could you have another array with the key value pairs swapped?
So the answer would be arrayKeyValueReversed['20101102'] = '20910930923';
When you sort the array, use the first item (array[0]) as the key to get the value in the arrayKeyValueReversed.