Accessing object in array using string - javascript

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"

Related

javascript adding a property to all objects in an array

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

Calling a variable to reference an array

I am trying to call a string variable to reference an array variable.
message1[0][0] = "Hello."; // existing array
var caller = ['message1', 'message2', 'message3'];
alert(message1[0][0]);
But instead of using the message1 array in the alert, I want to use caller[0] (which is equal to "message1") so that it displays "Hello". How do you do this? This doesn't seem to work:
alert(caller[0][0][0]);
The best way is to put message1 on an object, then use [] notation to index into the object:
var obj = {
message1: [
["Hello.", "two", "three"]
]
};
var caller = ['message1', 'message2', 'message3'];
alert(obj[caller[0]][0][0]);
If message1 is a global variable, it's already on an object — the global object, which you can access as window on browsers. So if it's a global, you could use:
alert(window[caller[0]][0][0]);
But global variables are a Bad Idea(tm), so best to use your own object instead.
Full disclosure: You can also use eval to do it, but it's a big hammer for a task this small. Just for completeness:
alert(eval(caller[0] + "[0][0]"));
I don't recommend it, but provided you're fully in control of the text you pass into it, it's workable. Much better to use an object, though.

breezejs: reject changes to specific property

Is it possible to reject the changes to a single property of a breeze object without rejecting ALL the changes to that object?
Say I have
// assume manager is an EntityManager containing a number of preexisting entities.
var person = manager.createEntity("Person");
// assume Name and House are valid properties of a Person object
person.Name("Jon Snow");
person.House("Lannister");
But I ONLY want to discard the changes made to the objects House property.
Is this possible, if so, how would I go about doing it?
Note: I would rather not iterate of the originalValues property and just replace them like that. I guess, I'm looking for a more graceful solution like...
person.House.rejectChanges();
where rejectChanges() is called on the property itself or something like that.
For the lack of a better solution I came up with the following code which seems to serve my purposes:
function RevertChangesToProperty(entity, propertyName) {
if (entity.entityAspect.originalValues.hasOwnProperty(propertyName)) {
var origValue = entity.entityAspect.originalValues[propertyName];
entity.setProperty(propertyName, origValue);
delete entity.entityAspect.originalValues[propertyName];
if (Object.getOwnPropertyNames(entity.entityAspect.originalValues).length === 0) {
entity.entityAspect.setUnchanged();
}
}
}
If person.House property has an entityAspect, you can call rejectChanges() on this property's entityAspect. Property has an entityAspect if it is an object, that has other properties. Simple type like string or Int does not have entityAspect, properties of simple type just belong to another object
person.House.entityAspect.rejectChanges()

Find item by key in 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]);

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