Perform search inside javascript object and return value

Asked

Viewed 1,136 times

1

i need to do a search inside a javascript object that brings me the sku according to size and color, vcs can give me a light?

Example: I need to insert in a variable the product sku that has the color "Blue" and size "Queen". In this case it would be the SKU 132

var produtos = {
skus:[{
    especificacao: {
        cor: "Azul",
        tamanho: "Queen"        
    },
    sku: 132
}, {
    especificacao: {
        cor: "Branco",
        tamanho: "Queen"
    },
    sku: 133
}]
};
  • You can use the Function filter within another Function that gets the color and size. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filtro

  • The two answers are good, but the other not marked with is also compatible with Internet Explorer (the one that was checked is not).

  • thanks for the information. As the two worked for me, I will accept your suggestion.

2 answers

4

Ok, but first let’s create a valid object, because the stated question is not.

var produtos = {
    skus:[{
        especificacao: {
            cor: "Azul",
            tamanho: "Queen"        
        },
        sku: 132
    }, {
        especificacao: {
            cor: "Branco",
            tamanho: "Queen"
        },
        sku: 133
    }]
};

To search for an object in an array, you can use the method find. The find method takes a callback, and invokes this callback by passing by parameter each object of your array, just return true for when the object meets its criteria.

var skuEncontrado = produtos.skus.find(sku => sku.especificacao.cor === 'Azul' && sku.especificacao.tamanho === 'Queen');

2


You can use the filter, would be something like:

var produtos = {
    skus: [
        {
            especificacao: {
                cor: "Azul",
                tamanho: "Queen"
            },
            sku: 132
        },{
            especificacao: {
                cor: "Branco",
                tamanho: "Queen"
            },
            sku: 133
        }
    ]
};

var list = produtos.skus.filter(function(item){
    return (item.especificacao.cor == 'Azul' && item.especificacao.tamanho == 'Queen');
});

console.log('Lista de Produtos: ', list);

Browser other questions tagged

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