Returns all the relevant elements of an array of objects?

I have an array consisting of objects with two properties.

One property of value is a number from 1 to 6. Another property of id is a number from 1 to 200.

How can I return the id property for all objects with "value" = 1 and write them to a new array?

+6
source share
4 answers

You must call the Array.prototype.filter function.

 var filteredArray = YourArray.filter(function( obj ) { return obj.value === 1; }); 

.filter() requires returning the desired condition. It will create a new array based on the filtered results. If you want to work with filtered Array , you can call more methods, for example in your .map() instance

 var filteredArray = YourArray.filter(function( obj ) { return obj.value === 1; }).map(function( obj ) { return obj.id; }); console.log( filteredArrays ); // a list of ids 

... and somewhere in the near future we can eventually use the Arrow functions for ES6, which makes this code even more attractive:

 var filteredArray = YourArray.filter( obj => obj.value === 1 ).map( obj => obj.id ); 
+16
source

Pure JS .... there are no filter / map functions that are not available for IE <9

 var array = [ {id:10, value:2}, {id:11, value:1}, {id:12, value:3}, {id:13, value:1} ], result = []; for(key in array) { if (array[key].value == 1) result.push(array[key].id); } 
+4
source

You can use a combination of Array.prototype.filter and Array.prototype.map .

First, filter only values โ€‹โ€‹with value equal to 1 .

 arr.filter(function (obj) { return obj.value === 1; }); 

Then you map the existing collection to a new array consisting only of id properties stored in the filtered array. So the final code is:

 var newArr = arr.filter(function (obj) { return obj.value === 1; }).map(function (obj) { return obj.id; }); 
0
source

Good news: easy, just write

 [ for (obj of array) if (obj.value === 1) obj.id ] 

The bad news is that it will take some time before you can depend on all browsers. This is from a new version of the language called "ES6". But you can try it now in Firefox!

0
source

Source: https://habr.com/ru/post/977979/


All Articles