Is it too expensive to search directly for the key?

Asked

Viewed 36 times

-5

var products = {};

for(var i = 0; i < 300; i++){
    products["product" + (i + 1)] = {}
    products["product" + (i + 1)]["qtd" + (i + 1)] = i + 1
}

//Busca pela key
console.log(products["product" + 400]); //undefined
console.log(products["product" + 299]); //{qtd299: 299}
console.log(products["product" + 22]); //{qtd22: 22}
console.log(products["product" + 301]); //undefined
//Assim fica até mais fácil fazer a busca:
if(products.product400){
    if(products.product400.qtd400){
    console.log(products["product" + 400]["qtd400"]);//não acha
    }
}
if(products.product200){
    if(products.product200.qtd200){
    console.log(products["product" + 200]["qtd200"]);//200
    }
}

//Busca fazendo loop
console.log(search("product" + 400))//null
console.log(search("product" + 299)) //{qtd299: 299}
console.log(search("product" + 22)) //{qtd22: 22}
console.log(search("product" + 301)) //null

function search(name){
    for (var k in products) {
        if (k == name) {       
            return products[k];
        }
    }
    return null;
}

https://jsfiddle.net/mw8v9jkf/

What are the best approaches? Is it good practice to take the first approach? In the second mode I need to create a loop to traverse the object...

1 answer

2


The optimal approach depends on your knowledge of the javascript object properties. If you know the name of the property, the best approach is to access it with the .. Thus, no query needs to be made because you directly access the object property:

//Busca pela key
console.log(products.product400); //undefined
console.log(products.product299); //{qtd299: 299}
console.log(products.product22); //{qtd22: 22}
console.log(products.product301); //undefined

If you do not know the name of the property of the object, then you can use the [] to access the properties dynamically, using the key search (your alternative 1). In Alternative 2, you are simply reimplementing the search for properties in a Javascript object, and so the best approach is to use access via key ([]), that is already native.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.