简体   繁体   中英

Extract key values from one Array object and filter from other objects with the extracted values with underscore javascript

var myArray = [{
    "name": "John Doe",
    "age": 29
}, {
    "name": "Anna Smith",
    "age": 24
}];

var myAnotherArray = [{
    "name": "John Doe",
    "age": 29
}, {
    "name": "Anna Smith",
    "age": 24
}, {
    "name": "Peter Jones",
    "age": 39
}, {
    "name": "Gabby",
    "age": 24
}, {
    "name": "Julian",
    "age": 29
}, {
    "name": "George",
    "age": 39
}];

I want to extact all age values from first array and then filter extracted values of age from second array.

You can use pluck to get the array of all the age from myArray . And then you can use filter , to filter the another array based on the age.

Demo

 var myArray = [{ "name": "John Doe", "age": 29 }, { "name": "Anna Smith", "age": 24 }]; var myAnotherArray = [{ "name": "John Doe", "age": 29 }, { "name": "Anna Smith", "age": 24 }, { "name": "Peter Jones", "age": 39 }, { "name": "Gabby", "age": 24 }, { "name": "Julian", "age": 29 }, { "name": "George", "age": 39 }]; var ages = _.pluck(myArray, 'age'); var filtered = _.filter(myAnotherArray, function(i, l) { return _.contains(ages, i.age); }); console.log(filtered); document.write(JSON.stringify(filtered));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM