Select a property from an array of objects based on a value : Javascript
You can use reduce
and check if the checked
property is true, then push
(As pointed out by assoron) the value to the accumulator - there is no need for 2 loops:
const arr = [
{ "value": "abc", "checked": true },
{ "value": "xyz", "checked": false },
{ "value": "lmn", "checked": true }
]
const filtered = arr.reduce((a, o) => (o.checked && a.push(o.value), a), [])
console.log(filtered)
Firstly, that's not valid JS - you need to swap your brackets and braces. Arrays use []
, and objects use {}
, not the other way around.
Secondly, you should first filter
out the wanted objects based on the checked
property, then use map
to extract the properties you want:
const arr =[{"value":"abc","checked":true},{"value":"xyz","checked":false},{"value":"lmn","checked":true}];
const res = arr.filter(({ checked }) => checked).map(({ value }) => value);
console.log(res);
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);