You can use the method filter
to bring only the elements that have the desired key:
let specsFiltradas = specifications.filter(spec => spec.key == 'Valor');
This returns another array, containing only the elements that have the key key
equal to 'Valor'
.
To get the values, we can chain a call from map
, to transform each element of the array into its respective value:
let valores = specifications.filter(spec => spec.key == 'Valor').map(spec => spec.value);
Thereby, valores
is an array containing values. If you have more than one object whose key key
be it 'Valor'
, all will be returned. Ex:
let specifications = [
{key: "32\uFF0E32", value: null},
{key: "Valor", value: 15},
{key: "333\uFF0E33", value: null},
{key: "Valor", value: 14}
];
let valores = specifications.filter(spec => spec.key == 'Valor').map(spec => spec.value);
console.log(valores); // [15, 14]
If none of the elements have key
equal to 'Valor'
, the array will be empty.
The other answers suggested using find
or forEach
, which also works.
The difference is that find
returns only the first occurrence (if you have more objects with key
equal to 'Valor'
, only the first is returned):
let specifications = [
{key: "32\uFF0E32", value: null},
{key: "Valor", value: 15},
{key: "333\uFF0E33", value: null},
{key: "Valor", value: 14}
];
let valor = specifications.find(spec => spec.key == 'Valor').value;
console.log(valor); // 15
Also, you should check if the return is undefined
before taking the amount.
let specifications = [
{key: "32\uFF0E32", value: null},
{key: "abc", value: 15},
{key: "333\uFF0E33", value: null},
{key: "def", value: 14}
];
// não existe key igual a Valor, find retorna undefined e
// ao tentar pegar o valor diretamente, dá um TypeError
try {
let valor = specifications.find(spec => spec.key == 'Valor').value;
} catch(e) {
console.log(e.name, e.message); // TypeError Cannot read property 'value' of undefined
}
// então vc tem que verificar se find retornou algo
let spec = specifications.find(spec => spec.key == 'Valor');
if (spec) { // nesse caso não entra no if
let valor = spec.value;
console.log(valor);
} else {
console.log('Valor não encontrado');
}
And forEach
will go through all the elements, then will catch the last occurrence:
let specifications = [
{key: "32\uFF0E32", value: null},
{key: "Valor", value: 15},
{key: "333\uFF0E33", value: null},
{key: "Valor", value: 14}
];
let valor;
specifications.forEach(item => {
if(item.key === "Valor"){
valor = item.value;
}
});
console.log(valor); // 14
Of course, if you only have one element that satisfies the condition, it doesn’t matter what method you use.