Let's say I have an array of four objects:
var jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ];
Is there a way that I can get the third object ({a: 5, b: 6}
) by the value of the property b
for example without a for...in
loop?
To get a list of duplicate objects in an array of objects with JavaScript, we can use the array methods. to get an array of value entries with the same id and put them into duplicates . To do this, we get the id s of the items with the same id by calling map to get the id s into their own array.
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
Filter
array of objects, which property matches value, returns array:
var result = jsObjects.filter(obj => { return obj.b === 6 })
See the MDN Docs on Array.prototype.filter()
const jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ] let result = jsObjects.filter(obj => { return obj.b === 6 }) console.log(result)
Find
the value of the first element/object in the array, otherwise undefined
is returned.
var result = jsObjects.find(obj => { return obj.b === 6 })
See the MDN Docs on Array.prototype.find()
const jsObjects = [ {a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8} ] let result = jsObjects.find(obj => { return obj.b === 6 }) console.log(result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With