Can't force object keys to be integer [duplicate] - javascript

This question already has answers here:
Keys in Javascript objects can only be strings?
(8 answers)
Closed 4 years ago.
const obj = {
15: 100
};
for(let key in obj)
console.log(key, typeof(key), typeof(+key))
The result is 15 string number. I'm trying to iterate over object values and put some of them into Map object but types compatibility seems unable to achieve. Am I doing something wrong here or object keys are always strings?
Object.keys(obj)
also returns ["15"]

Object keys are always strings. You can see more about it here:
Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.
For you to be able to achieve what you want you will need to cast the keys back to integers.

Related

I can't iterate over a javascript array [duplicate]

This question already has answers here:
How can JavaScript arrays have non-numeric keys?
(2 answers)
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 4 months ago.
I am going crazy here, I have an associative array as seen below which is defined after the page finishes loading. However Array.forEach is returning undefined and I have no idea why. The array is most definitely populated during the loop. Can anyone give me any ideas? Also doesn't work with JQuery's $.each
Arrays are usually a mapping of index (integer from 0 to 232 − 2, inclusive) to value. In your case you've treated the array as a dictionary e.g. key (string) to value.
You've probably done something like this:
members = new Array();
members['animerox1213'] = 'Ashima';
JavaScript allows this, after all it is still an object:
typeof members === 'object'
But instead of adding a value to the array, you've actually set a non-numeric property on the object called animerox1213. That is not how an array should be used and we can observe this by checking the size:
members.length === 0;
Consequently, forEach does not do anything as it considers it an empty array.
That said, it is enumerable with for…in as it's still just an object (with enumerable properties):
for (m in members) {
console.log(m, members[m]);
}
Consider using just an object e.g. members = {} or Map. Note especially the section Objects vs. Maps.

convert array(2) that has sorted object to object [duplicate]

This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Does ES6 introduce a well-defined order of enumeration for object properties?
(3 answers)
Closed 1 year ago.
I'm trying to sort an object from db
MyOjbect : {
key: {
val1:"value",
val2:"",
val3:time,
val4:...
...}
}
and I sorted the object by val3
const sorted = Object.entries(MyObject)
.sort((x,y) => {x[1].val3 - y[1].val3} );
and got an array type.
0:(2) ["key" , {val1:...val2:...}]
1:(2) ["key" , {val1:...val2:...}]
...
I tried reduce() to make it back to the object type, but it changes to be in unsorted order
How can I keep the order sorted and change the type to the object?
You can't. An object doesn't keep the sort order as an Array does it. If you want to have the keys sorted you need to use an Array.

how to access values in javascript's object? [duplicate]

This question already has answers here:
Setting and getting object to local storage using stringify?
(4 answers)
Closed 8 months ago.
I am trying to iterate through the values in an object.
Here are the values of the object:
object=Object.values(localStorage)[0];
console.log(object);
Output
{"name":"e7","id":"7","category":"n"}
I tried:
console.log(object[0]);
But it printed just "{"... Then I tried... object[name], object['name'] , object[0][0]... but the output is not satisfactory...
I want to loop through these values like I want to access "name" and its value and so on...
Can I loop through individual values of JavaScript?
the output is actually a value ..
Local storage can only store strings, so what you get from it is just a JSON string and you have to parse it into a JavaScript object before you can use it like one.
The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings).
You can do it by calling JSON.parse() (documentation here).
var fromLocalStorage = '{"name":"e7","id":"7","category":"n"}';
// Parse the JSON string from localStorage into a JS object
var object = JSON.parse(fromLocalStorage);
// Get a single property
console.log(object.name);
// Loop all the key-value pairs of the object
Object.keys(object).forEach(function(key) {
console.log(key + ' -> ' + object[key]);
});

Why does JavaScript allow accessing an object's property using an array of length 1, as if the array was just the single element itself? [duplicate]

This question already has answers here:
Why does JavaScript convert an array of one string to a string, when used as an object key? [duplicate]
(4 answers)
Why can I access object property with an array?
(2 answers)
Closed 2 years ago.
See this example:
> map = { 5: 'five' }
> map[5]
'five' // Makes sense
> arr = [5]
> map[arr]
'five' // Does not make sense
> arr = [5,6,7]
> map[arr]
undefined // I'm cool with that
So when I access an object's property with an array of length 1, it behaves as if I simply input the single element instead of the array. But when the array's length is anything but 1, it will produce the expected behavior.
What is the purpose of this behavior? To me this would simply make things harder for a developer to find a bug in their code.
If an object index is not a string or Symbol, it's converted to a string as if by its toString() method.
array.toString() performs the equivalent array.join(",").
So
map[arr]
is equivalent to
map[arr.join(",")]
If the array has one element, joining it simply returns that one element converted to a string, so it's equivalent to
map[arr[0].toString()]
and that explains your first result.
But in your second example, it returns the string "5,6,7" and there's no property with that name in the object.

Does ordering in javascript JSON Objects for integer and string keys exist? [duplicate]

This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Closed 4 years ago.
I was trying out different objects and I noticed a little strange behavior in Javascript JSON objects. Would be great if someone can elaborate.
Example:
var bat={ 3:"FA", 7:"WER", 1:"JWRT",d:"EWR",a:"bA",8:"ADB"};
For this Json object, when it has integers as keys (works even if you enclose the integers in double quotes), and when you try to get the keys using Object.keys() or by simply printing bat the following order is seen.
{1: "JWRT", 3: "FA", 7: "WER", 8: "ADB", d: "EWR", a: "bA"}
The ordering does not happen automatically for Json Objects when the keys are strings (even if it is a Json Object containing string keys exclusively, or has integer and string keys interspersed).
In the case where there are string and integer keys in the same Json Object the integers get to the beginning of the array of keys.
Is there some reason for this behavior? Thanks in advance...
The order of object keys is never guaranteed. Even when you use numeric keys, they are internally strings.
From the ECMA Specification:
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.

Categories