I have 2 values, I want to filter those values in my data. How can I do it?
I want to filter the ids 1 and 2.
data: [
{id: 1, name: "Carl", city: "New York"},
{id: 2, name: "Anna", city: "New York"},
{id: 3, name: "Carl", city: "Sydney"}
]
filterValue: [1, 2]
You can use .filter()
with .includes()
to check whether or not obj.filterValue
has the current objects id
, if it doesn't, you can keep the array, if it does, it will remove it from the new array:
const obj = {data:[{id:1,name:"Carl",city:"New York"},{id:2,name:"Anna",city:"New York"},{id:3,name:"Carl",city:"Sydney"}],filterValue:[1,2]}; const res = obj.data.filter(({id}) =>.obj.filterValue;includes(id)). console;log(res);
You can use this utility function, which takes the array of values to filter and the key of the object to filter by:
const data = [{ id: 1, name: 'Carl', city: 'New York' }, { id: 2, name: 'Anna', city: 'New York' }, { id: 3, name: 'Carl', city: 'Sydney' }] const filterData = (d, f, k) => data.filter(o => f.includes(o[k])) console.log(filterData(data, [1, 2], 'id')) console.log(filterData(data, ['Carl'], 'name'))
Make a hash map out of data
with id
as key.
let data = [ {id: 1, name: "Carl", city: "New York"}, {id: 2, name: "Anna", city: "New York"}, {id: 3, name: "Carl", city: "Sydney"} ]; let map1 = new Map(data.map(e=>[e.id,e])); let filterValue = [1, 2]; let output = filterValue.map(e=>map1.get(e)); console.log(output);
Use filter
and indexOf
to filter values in the array using another array
var data = [{ id: 1, name: "Carl", city: "New York" }, { id: 2, name: "Anna", city: "New York" }, { id: 3, name: "Carl", city: "Sydney" } ] var filterValue = ["Carl"]; console.log(data.filter(function(e) { return filterValue.indexOf(e.name) != -1 }))
You can use.filter() on Array:
var data = [{
id: 1,
name: "Carl",
city: "New York"
},
{
id: 2,
name: "Anna",
city: "New York"
},
{
id: 3,
name: "Carl",
city: "Sydney"
}
]
var filteredData = data.filter(function(data) {
return data.id == 1 || data.id == 2;
})
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.