-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...
When in doubt you can always test which is the fastest.
– fernandosavio