Object complexity while search by key [duplicate] - javascript

This question already has answers here:
Complexity of accessing data in an object
(2 answers)
Closed 1 year ago.
I have the following object:
let obj = {
"name": "someName",
"age": 33,
"city": "someCity"
}
I understand that an object is not indexed
"JS objects have no defined order, they are (by definition) an
unsorted set of key-value pairs."
so what is the complexity of:
let result = obj.name
Is it searching all over the object to find the right key?
Is there a way to index this object so complexity will be O(1)?

Data access which involves retrieving or modifying data stored in an object is done in constant time O(1). This is also true for the insertion and removal of data.

Related

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.

Is Object and Array in Javascript the same thing? [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Are Javascript arrays primitives? Strings? Objects?
(7 answers)
Closed 2 years ago.
I'm looking for an elegant way of understanding JavaScript array and objects.
I came to an anomaly in which I got stuck.
Since in PHP or other languages, when we make an array e.g
$a = [
admin => 1,
staff => 2
];
so if we want to access its element we can do so by for e.g $a[admin] and we will get 1.
similarly if its an object e.g
$a = (object) [];
$a->sadd = 'sas';
we can access it with arrow
$a->sadd
and if we try to access object elements in the style of array i.e like this $a['sadd'] it will throw error that you can not use it as array style.
But I was surprised by the anomaly in JavaScript.
I have observed that in JavaScript no matter what I am making, an array or object, the elements of both can be accessed via dot or via array style and i found no difference in there accessing style.
for e.g
var a = {sadd : 1}
I can access its element via a['sadd'] or a.sadd both will give 1
So I am confused by this anomaly and wondering whether array and object both datatypes are considered same in JavaScript?
An array is indeed an object.
Javascript is a dynamic language and accepts mixed types of entities. Also while accessing, dot notation seems to be more clearer (atleast imo) and is preferred. Bracket notation is used for dyanamic keys.
The difference between array and objects boils down to their usecase:
Array -> Contiguous block of memory
Object -> key-value pair (like a dictionary)
Your php example is actually creating what we'd call an object in JS, not an array. In JS an array is a list of items, which you can find items by array[i], or by looping.
An object is a collection of fields, which you can go into by object.fieldName or object[fieldName].
This can be confusing in JS though, because theoretically everything is an "object", including arrays, due to the way things are handled lower down..
I would recommend following along with the https://justjavascript.com/ course for good mental models on how objects work in JS.

Sort v-for over an object (Vue2) [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Sort JavaScript object by key
(37 answers)
Closed 4 years ago.
I am using Vue2 and try to sort a v-for. I am iterating over an object and the vue-doc states:
When iterating over an object, the order is based on the key
enumeration order of Object.keys(), which is not guaranteed to be
consistent across JavaScript engine implementations.
My v-for without sorting looks like this:
<my-component :key="key + value + uid"
v-for="(value,key) in myObject" :key-prop="key"
:value-prop="value"></my-component>
How would I sort this if the Object.keys() are not consistent?
Edit: This is an example Object (returned from Rest-Service)
Chrome console logs this:
{
HUMID: "66%"
DAY: "true"
TEMP: "30"
}
The actual object is much larger.
Edit2:
With the help of "Oli Crt" I solved this. I wasn't able to calculate the sortedObjects as a computed property in my case, but I triggered it on getting the Response of my Rest-Service.
sortObject: function() {
this.myObjectSorted = Object.keys(this.myObject).sort();
}
This results in the following Object:
{
0: "DAY"
1: "HUMID"
2: "TEMP"
}
By taking the value of this sorted Object as my key-prop and getting the actual value (66%, true, 30) of the unsorted Object with
myObject[value]
I got the desired result.
<my-component :key="key + value + uid"
v-for="(value,key) in myObjectSorted" :key-prop="value"
:value-prop="myObject[value]"></my-component>
I think you should use a computed property.
You could sort the keys of your object
computed: {
myObjectSorted: function () {
return Object.keys(this.myObject).sort(...); // Do your custom sorting here
}
}
Then use myObject[key] with the key from myObjectSorted in v-for.

Javascript object traversal in wrong way [duplicate]

This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have a json object in occupancy_list as follows :
I am traversing the object as follows :
for(var prop in occupancy_list)
{
console.log(prop);
}
I am getting values in reverse order. Like at first Room 2 then Room 1. How can I fix it ?
Object properties are unsorted and could always be random. If you need order - get the keys, and iterate them that way:
Object.keys(occupancy_list).sort(function(a, b) {
//sort logic
}).forEach(key) {
//logic on each key
});

JavaScript Objects and for in loops [duplicate]

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
I'm working my way through a tutorial and I have hit a snag.
I created this object and I'm trying to loop through and print the first names of the entries. I thought it was working, but then I noticed that when I change 'firstName' in my for loop to 'number' or 'lastName', it still writes the first names to the console.
Can anyone shed some light for me? Thanks!
var friends = {
bill:{
firstName:"Bill",
lastName:"Gates",
number:"617-333-3333",
address:["One Microsoft Way", "Redmond", "WA", "98052"]
},
steve:{
firstName:"Steve",
lastName:"Jobbs",
number:"617-222-2222",
address:["15 Idontknow Street", "No Idea", "NO", "33333"]
}
};
var list = function(friends){
for (var firstName in friends) {
console.log(firstName);
}
}
The property names of your "friends" object are "bill" and "steve". That's what the loop iterates through — the property names. It doesn't matter what variable name you use.
What your loop is currently printing is "bill" and "steve", not "Bill" and "Steve". If you want to log the properties of the objects referenced by the properties of the "friends" object, you have to access those objects. If you wanted the "number" for example:
for (var fn in friends) {
console.log(friends[fn].number);
}

Categories