Find item by key in Javascript - javascript

Quick rookie question please.
Suppose I have a javsacript object like so:
var meh=[["cars",27], ["bikes",85], ["skates",4]];
To go through each data object here, I can do this:
$.each(meh, function(index,value){
console.log(value) //returns ["cars",27] etc..
});
And considering I know the place of, say, cars, I can do this to access it:
console.log(meh[0][0]) //shows "Cars"
and of course, if I want the value of cars, I need to do this:
console.log(meh[0][1]) //Shows 27
Now, I have the string - Keys, like cars, bikes or skates
But I cant figure out this: How do I access their respective values?
meh["cars"] is returning undefined, since, as I understand, it cant find a description outside each object.
I can do meh[0]["cars"] but it defeats the point as the position of cars might change.
How do I access a value of something with their key please?
thanks.

You should change that to objects
var meh={"cars" :27 , "bikes" :85, "skates" :4};
Now you can simply access it via keys
alert(meh['cars']); //27

If you have access to the code and can change the object, change it to something like this:
meh = {
'cars': 27,
'bikes': 85,
'skates': 4
};
and you can access them with keys like
meh["cars"] //will give you 27
If you cannot change the code, then the only way I see is using jQuery.each and comparing each key with your known key and assigning it to a temp variable.

Use an object instead:
var meh = {
"cars": 27,
"bikes": 85,
"skates": 4
};
You can iterate over it using $.each():
$.each(meh, function (key, value) {
// key == "cars" and value == 27, etc.
});
Accessing values works like this:
meh.cars
which is equivalent to this:
meh["cars"]
Obviously, the second notation can be used with variables.

You have your data structure in an array, so you are always going to have to access by the array syntax e.g. [0][1]. The arrays in JavaScript are not associative. You could write a helper function which iterates around the array looking for the key you specify and returning the value back. Or you could change your data structure to be Objects, which do support key lookup.

If you can't alter the object, you can create a map to make managing the indices simple. E.g.
map = {
'cars': 0,
'bikes': 1,
'skates': 2
};
Then, you can do:
alert(meh[map['cars']][1]);

Related

Getting Key name of an Object item

Before marking this as a duplicate, i've spent a lot of time looking through similar question and most of the answers did not solves my situation.
i have a huge list of items as objects by IDs. like this, in a Map (userDB)
{
"15321":{name:"name1",status:"status1"},modules:{...},
"15322":{name:"name1",status:"status1"},modules:{...},
"15323":{name:"name1",status:"status1"},modules:{...}
}
now i need to make an operation in which i need all these IDs, in that case, the key names of every item on it. i need to get these "15321","15322" etc.
more specifically i wanted something that i could fetch in something like
userDB.forEach( u => {
//something here to get u's key
})
i've tried Object.keys(), but it will return a list of IDs as an object
{"15321","15322"...} in which i still cant grab the ID string
i've tried for (i in Object.keys(userDB)) too, no successs
i double-checked for silly syntax errors and everything of the sort.
Things that will be nice to get in mind to answer this:
dont try to show me a new way of storing stuff, it is already stored so you will not be of help
the result SHOULD be the ID as a string, the name of the key.
dont ask "why i want to make this". just answer and dont try to change this scenario. because this is what i've seen in most of the other similar questions and it is what makes me walk in circles every time.
TL;DR. i just want to get the parent key names of the object im currently processing
Object.keys(obj) will return an array.
But in your data there is another key modules except IDs.
So you can use this :
var keys = Object.keys(data);
keys.pop();
console.log(keys); // ["15321", "15322", "15323" ...]
You might be confused. Object.keys(obj) returns an array. In your case it looks like this: ["15321", "15322", "15323"]. You could iterate through that array like so and you'll have both the key and the object and you'll be able to do with them whatever you want. Below is a for loop that attaches the key to the object as a key named 'key'.
var keys = Object.keys(myObject);
for(var i = 0; i < keys.length; i++){
var key = keys[i]; // this is your key
var obj = myObject[key]; // this is the key's value
obj.key = key;
}
EDIT
In javascript an Array is also an object, but the 'keys' so to speak are usually numbers instead of strings. So an array that looks like this:
["Hello", "there"] is essentially represented like this: { 0 : "Hello", 1 : "there" }
When using for-in on an array, it'll loop through the keys, but those keys will be 0, 1, 2... instead of the items themselves.

How do I access the second item in this Javascript object?

This is probably really simple but I have a statement...
console.log($scope.data);
And in the console window I see...
[pension: "123", postcode: "GL"]
I have two questions...
What type of object is this?
How do I get access to the value (rather than the key) with a for
loop?
I tried...
for (item in $scope.data) {
console.log(item[1]);
}
But all I get is...
e
o
Not I cannot use the 'pension' or 'postcode' I need to be able to iterate the collection.
I was thinking I would need to use JSON.parse? But this seems like an overkill, because I originally instantiated $scope.data as an array. So why cant I access it like an array?
That's just how for..in loops work. The keys are assigned to item one by one, and then you use $scope.data[item] to get the value of that particular key.

Accessing object in array using string

I have this code:
var dictionary=[
apple={name:"apple",pos:"noun",d:"",c:["fruit"]},
banana={name:"banana",pos:"noun",d:"",c:["fruit"]}
];
How could I access one of the objects in the array by using a string of its name. In the way that you could access an object as
object['propertyName']
is there a way to do something similar with an array? I want to access it in a way like
dictionary["apple"].pos
//Want to return "noun"
Is there a simple way to do something like that with an array, and if not is there an alternative method that I could use?
The way you're generating your dictionary s wrong; it's syntactically valid, but it's almost certainly not what you intended to do. It's not binding the key apple to that object. Rather, it's defining an implicit (global) variable named apple and assigning the object to that, as well as the first element of the array.
Try this:
var dictionary= {
apple: {name:"apple",pos:"noun",d:"",c:["fruit"]},
banana: {name:"banana",pos:"noun",d:"",c:["fruit"]}
};
console.log(dictionary["apple"].pos); // "noun"
// This also works:
console.log(dictionary.apple.pos); // "noun"

JSON object: Get all objects to capitalize their first letters

I have a JSON object that looks something like this (result from an AJAX call):
json{
code: 0,
resultVal: Object {
data:
[
Object{
generatedName: name1,
generatedValue: value1
},
Object{
generatedName1: name2,
generatedValue1: value2
}....
],
anotherItem: true,
...
}
}
To clarify resultVal is an object and data is an array of objects, and each object in that array will have two values who's names I will not know in advance.
I am having a problem because I need generatedName and generatedValue to be GenerateName and GeneratedValue. These names and values are usually not the as each other. I know can access each Object through json.resultVal.data[#], but that's as far as I have gotten. json.resultVal.data[0].name returns undefined.
Once I can get those values isolated I can make the fixes I need.
NOTE I am running these calls through Chrome's debugger. The thinking is once I am able to isolate the value I can write the code to fix it using that call. It takes some time to get to this point in the application.
Any suggestions?
If I understood it right, you need to iterate over all keys for all objects in "json.resultVal.data". Try using a for/in loop to iterate over the "data" object, as in:
for( var i in json.resultVal.data ) {
for( var k in json.resultVal.data[i] ) {
/* here "k" will be key string ("generatedName", "generatedValue", ...) */
}
}

How do I access the first key of an ‘associative’ array in JavaScript?

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.

Categories