Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - Take object out of array based on attribute value

My array looks like this:

array = [object {id: 1, value: "itemname"}, object {id: 2, value: "itemname"}, ...] 

all my objects have the same attibutes, but with different values.

Is there an easy way I can use a WHERE statement for that array?

Take the object where object.id = var

or do I just need to loop over the entire array and check every item? My array has over a 100 entries, so I wanted to know if there was a more efficient way

like image 981
Nicolas Avatar asked Mar 03 '17 13:03

Nicolas


People also ask

How do you get a specific value from an array object in TypeScript?

Use the map() method to get an array of values from an array of objects in TypeScript, e.g. const ids = arr. map((obj) => obj.id) . The map method will return a new array containing only the values that were returned from the callback function. Copied!

How do you remove an object from an array from a property?

To remove an object from an array by its value:Call the findIndex() method to get the index of the object in the array. Use the splice() method to remove the element at that index. The splice method changes the contents of the array by removing or replacing existing elements.

How do I remove something from an array in TypeScript?

To remove an object from a TypeScript array:Use the findIndex() method to get the index of the object. Use the splice() method to remove the object from the array. The splice method will remove the object from the array and will return the removed object.

How do you find an element in an array of objects in TypeScript?

To find an object in an array by property value: Call the find() method on the array. On each iteration, check if the value meets a condition. The find() method returns the first value in the array that satisfies the condition.


1 Answers

Use Array.find:

let array = [     { id: 1, value: "itemname" },     { id: 2, value: "itemname" } ];  let item1 = array.find(i => i.id === 1); 

Array.find at MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

like image 166
Saravana Avatar answered Sep 29 '22 08:09

Saravana