I have an array of objects with the following structure:
var arr = [ { "value": "abc", "checked": true }, { "value": "xyz", "checked": false }, { "value": "lmn", "checked": true } ]; let result = arr.filter(item => item.checked); console.log(result);
I would want the output to be:
["abc", "lmn"]
Because those two value
s have checked: true
.
I have tried filtering out based on checked value:
let result = arr.filter(item => item.checked);
I am getting the objects that has checked
property value that is set to true
.
Help would be appreciated.
Answer: Use the find() Method You can simply use the find() method to find an object by a property value in an array of objects in JavaScript. The find() method returns the first element in the given array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
use filter and map:
const arr =[{"value":"abc","checked":true},{"value":"xyz","checked":false},{"value":"lmn","checked":true}]; const result = arr.filter(res=>res.checked).map(ele=>ele.value); 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