Find an object in the array that has a specific key

Asked

Viewed 530 times

2

I have the following object array:

specifications: Array(63)
0: {key: "1", value: null}
1: {key: "11\uFF0E11", value: null}
2: {key: "155\uFF0E50", value: null}
3: {key: "2", value: null}
4: {key: "200\uFF0E00", value: null}
5: {key: "2222\uFF0E22", value: null}
6: {key: "222\uFF0E22", value: null}
7: {key: "22\uFF0E22", value: null}
8: {key: "24\uFF0E24", value: null}
9: {key: "25\uFF0E25", value: null}
10: {key: "26\uFF0E26", value: null}
11: {key: "27\uFF0E27", value: null}
12: {key: "28\uFF0E28", value: null}
13: {key: "29\uFF0E29", value: null}
14: {key: "3", value: null}
15: {key: "3000\uFF0E00", value: null}
16: {key: "300\uFF0E00", value: null}
17: {key: "30\uFF0E30", value: null}
18: {key: "31\uFF0E31", value: null}
19: {key: "32\uFF0E32", value: null}
20: {key: "33", value: null}
21: {key: "333\uFF0E33", value: null}
22: {key: "Valor", value: 14}

I need to find in this array the key that has name Valor and assign to a variable the value contained in the key value.

I thought I’d do it this way:

for(let i=0;i<this.specifications.length;i++){
   if(this.especifications[i].key == "Valor"){
      minhaVariavel = this.specifications[i].value
   }
}

It works, but I wonder if Typescript provides some other way, maybe more lean, to find this object?

3 answers

4


3

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.

1

this.specifications.forEach( item ->{
  if(item.key === "Valor"){
      minhaVariavel = item.value
   }
})

Always remember to use ===, so it checks the type of the variable and the value. Using ==, the comparison is only of the value, then 2 == '2' would return true.

Browser other questions tagged

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