Can you give an object a key in javascript? - javascript

If you have an array of objects like
[{rID:53, name:Roger, age:43},{rID:12, name:Phil, age:22}]
is it possible instead to give each a object a key like
[53:{name:Roger, age:43},12:{name:Phil, age:22}]
?
I understand that each object has an index number, but I'm looking for a way to find objects not based on their index pos, and preferably without having to loop through until you find an object with rID=53 type thing.
I'd be using PKs from mysql rows to give each object it's key.
Cheers

If you want an unordered collection of variables with arbitrary keys. Then use an object.
{"53":{name:Roger, age:43},"12":{name:Phil, age:22}}
Arrays can have only numeric keys, but if you want to assign a value to an arbitrary position, you have to do so after creating the array.
var some_array = [];
some_array[53] = {name:Roger, age:43};
some_array[22] = {name:Phil, age:22};
Note that this will set the array length to 54.
Note that in both cases, you can't have multiple values for a given property (although you could have an array of values there).

You need an object for that.
{
53: {
name: "Roger",
age: 43
},
12: {
name: "Phil",
age: 22
}
}

No. You cannot have a key and an index in a js array. Arrays only have indices, Objects only have keys. There is no such thing like a associative array in JavaScript. If the order (of your original array) does not matter, you can use an object though:
{53:{name:"Roger", age:43},12:{name:"Phil", age:22}}

You can use objects to do this
var map = {"53":{"name": "Roger", "age": "43"},"12":{"name": "Phil", "age": "22"}};
Then access the value like an array (note, i'm using string because that's what keys are stored as, strings, you can access it using an integer, but it will just be converted to a string when searching for the property anyway):
map["53"]
You can also loop through this map object:
for (var key in map) {
var value = map[key];
}

Related

how to get values of specific key in javascript

I have this Object
const fruits = {
apple: 28,
orange: 17,
pear: 54,
};
I want to insert the values from the key "apple" into an empty array
with Object.values.fruits I get all the values, so I tried it with Object.values(fruits.apple) to specify the key
const leere_liste = [];
const values = Object.values(fruits);
leere_liste.push(values);
but this gives my an empty array, is there a method for that which I'm unaware of ?
Couple of things.
Its Object.values(fruits), not Object.values.fruits.
Object.values only works on objects. So while it will work on fruits, it won't work on a specific property of fruits unless that property contains an object too.
Works:
const fruits = {apple: 28, orange: 17, pear: {a: 54, b: 22}};
console.log(Object.values(fruits.pear));
// [54, 22]
Also, since you're getting an array back from Object.values, if you push that onto another array you'll just have an array containing an array of those values.
If you want a single dimensional array, simply assign it like:
const leere_liste = Object.values(fruits);
Not sure what " I get all the values, so I tried it with Object.values(fruits.apple) to specify the key" means, as in your code you are simply getting the values of the entire array, not just apple, and also the property apple itself doesn't have "values", it has only one value.
Object.values is a function that takes an object as a parameter and returns an array of all of the values of the object only, usually in alphabetical order of the keys, but the actual final product has no connection to the original keys or the object, just given it itself it would be impossible to determine what values correspond to what keys
Hence it's a bit difficult to understand what you are trying to do, if you are trying to only insert the value of "apples" into an empty array, I don't know why you can't just do emptyArray.push(fruits.apple), if you are trying to make a method for pushing the value of any given fruit to an array, you can simply use bracket notation on a function const fruity= (arr, obj, key) => arr.push(obj[key]) then to use it with your variables fruity(leere_liste, fruits, "apple")
If you want to convert the keys AND values into a new kind of array that you can work with, then what you need is Object.entries, it is a function that takes an object as a parameter and returns a two dimensional array, with the first element of each sub array representing the key of the respective object property, and the second element of each sub array representing the corresponding value to said key of the original object.
To use it just call var newArray=Object.entries(fruits), in general this is helpful if you want to modify objects using expressions, such as Array.map, Array.forEach etc, although I'm not sure if you need it to simply add a property of an object to an array, to do that, see paragraphs above

How to get the correct array length

In my code i initialize array then put a value inside it why the output be 0 ?in spite of this should be 1
var changedfields=[];
changedfields['product']="productname";
alert(changedfields.length);
You're creating an associative array (normal arrays have an numeric index) but are actually trying to build a HashMap (a key, value pair). Use Objects or ES6 Maps.
I hope the following example will help you out:
var changedfields = {}; // create an object
changedfields['product']="productname";
var keys = Object.keys(changedfields); // returns the keys of the object ['product']
alert(keys.length);
I would suggest to read more about datastructures in javascript and avoid associative arrays in general.
Length of a JavaScript object (that is, associative array)
associative array versus object in javascript
Your question is interesting. Following is the answer.
First of all Arrays in Javascript are object type.
The first line you wrote creates an empty array and it's type is object.
var changedfields=[];
The second line you wrote creates a property called product of changedfields and sets the value to productname. It allows you add the product property because Javascript Array type is object. If you just had var changedfields; you could not add this property.
changedfields['product']="productname";
The third line you wrote simply finds the length of the empty array.
alert(changedfields.length);
In Javascript associative arrays are achieved using object. But if you want to add the product name in changedfields array. You could use push method like below and check the length:
changedfields.push('productname');
console.log(changedfields.length);
Javascript numerical indexed array length
So the Javascript numerical indexed array length can be calculated this way:
console.log(array.length);
console.log(changedfields.length); // in your case
The Javascript associative array length
The Javascript associative array (object) length can be calculated following ways:
Option 1:
Object.len = function(obj) {
var objLen = 0;
for (i in obj) {
obj.hasOwnProperty(i) ? objLen++ : '';
}
return objLen;
};
console.log(Object.len(changedfields));
Option 2:
console.log(Object.keys(array).length);
console.log(Object.keys(changedfields).length); // in your case
Note: This has issues with Internet Explorer 8, Opera etc

JS. Object in array?

I'm learning js, find this code:
var arr = [
{id: 111, now: '12.02.2014'}
];
What is this? I know that var arr = [ ... ] - array, but what is {} in array and how i can work with this data and display this ?
{} is the syntax for creating an object. It's called an object initializer, but it's frequently called an "object literal".
So what you're doing there is creating an object which has id and now properties, and putting that object into an array as its only entry.
...how i can work with this data and display this ?
To display the id, for instance:
console.log(arr[0].id);
What that does:
arr[0] - retrieve the first entry in the array. In our case, it's an object.
.id - Get the value of the id property from that object.
We could also write it like this:
var obj = arr[0];
console.log(obj.id);
Alternately, if we didn't know in advance what property we wanted but we were given a string containing the name of the property, we could use [] with the object as well:
var nameOfProperty = "id";
var obj = arr[0];
console.log(obj[nameOfProperty]);
JavaScript has both the dotted syntax (obj.id), and the bracketed syntax (obj["id"]) for accessing object properties, where with the latter you can use any string (including one from a variable).
Yes, that is an object inside an array. In truth, all values, from numbers to functions to arrays, are actually objects.
You can access this object in the same way as you would any item of an array. (arr[0])
You can then access properties of the object, for example arr[0].id.
For more about objects, take a look at Objects on MDN.

How do I access members of a Javascript object numerically?

Let's say for example, I have the following Javascript object:
var Object = {
Person_A: { name: 'James', age: 40, country: 'Spain' },
Person_B : { name: 'Smith', age: 50, country: 'France' }
}
I want to know how many properties there are in the object Object, and access these properties numerically e.g. through Object[n].
Until now (I don't use Javascript objects much, but I do use JSON as a return format when working with AJAX) I didn't know that Javascript objects don't have a length method and can't be accessed numerically.
I've tried to convert the Javascript object into the same type of JSON that is returned when I make AJAX calls (the JSON is returned as an object with a length method, and is numerically accessible - just read another thread, and maybe I'm wrong about this - double checking now) using JSON.parse(JSON.stringify(Object)) but that simply returns the same exact Object.
So, my question is, what's the most efficient way to take an object like the example, and make it accessible numerically and have a length method.
Any help would be greatly appreciated (and please ask if you need any clarification of my question).
Thanks.
This cannot be done with meaning. The properties of JavaScript objects have no inherent order1.
The length property is a special member of Arrays. (Arrays are just objects that have a specific [[prototype]] and understand how to magically update length -- and have a few other internal rules defined -- that's it!)
Update for comment:
If the index is required, use an Array:
var people = [
{ id: "Person_A", data: { name: 'James', age: 40, country: 'Spain' } },
{ id: "Person_B", data: { name: 'Smith', age: 50, country: 'France' } }
]
people[0].id // "Person_A"
1 JSON "has order" only when serialized as text but implementations, including those that turn it into JavaScript objects, work without access [or assumption] about order; there is no order guarantee for properties per the JSON standard. Just because properties in an object "look" ordered in JSON (or a JS Object Literal), does not imply an order.
If you want to completely replace that object with an array accessible numerically, you could first loop through it to build that new array:
var newArray=new array();
for(i in object){
array.push(i);
}
You can now access that array numerically
function numericIndices(obj) {
var i=0, x;
for( x in obj) {
obj[i] = obj[x];
i++;
}
// next line is OPTIONAL:
obj.length = i;
}
Given an object, this will add the numeric indices to that object. So after running it through that function, the object will have both string keys and numeric keys. If you have the optional line too, you automatically get a length property as well.

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