Reputation: 333
I have a object that looks like this:
export default class Widget {
public title: string;
public url: string;
public icon: string;
public id: string;
public defaultWidget: boolean;
}
I have an array with all the widgets, allWidgets. I want to extract the id from this array WHEN the defaultWidget is true.
So I want to extract a property from this object (id) WHEN another property (defaultWidget) is true. So far I have:
const newArray = allWidgets.map(element => element.defaultWidget);
However, it only returns true for every true object it have. But I want it to return the ID where the defaultWidget is true.
Upvotes: 0
Views: 702
Reputation: 63
in JavaScript you can try this code: returns list of ids if married = true
// Try edit msg
var emps = [
{id: 1, name: "Employee1", married: true},
{id: 2, name: "Employee1", married: false},
{id: 3, name: "Employee1", married: true}
]
// getting list of ids of employees if married is true
var idList = emps.map(obj => {
if (obj['married'] == true) {
return obj.id
}
})
// removing null values from list
idList = idList.filter(ele => ele!=null);
console.log(idList);
// output: [1, 3]
Upvotes: 1
Reputation: 381
const newArray = allWidgets.filter(obj => obj.defaultWidget).map(obj => obj.id);
The above array will give you the list of id's where defaultWidget is true.
Here Filter will filters the array based on the condition and map creates a new array containing only id's
Upvotes: 2
Reputation: 2384
You could use filter to get widgets with defaultWidget === true
and then use map to get ids.
Both filter
and map
will create new arrays.
Or you could try use reduce to compose all of it.
In case of reduce
you will create new array once.
const newArray = allWidgets.filter(widget => widget.defaultWidget).map(widget => widget.id)
// or
const newArray = allWidgets.reduce((acc, elem) => {
if (elem.defaultWidget) {
acc.push(elem.id);
}
return acc;
}, []);
Upvotes: 3