我正在尝试优化从大表(对象数组)中选择数据。
我想从一行中保存多个值,然后写入 localStorage。
let customerTable = [
{
"customer": "Apple Computers",
"contact": "Steve Jobs",
"id": 1,
"city": "Cupertino"
},
{
"customer": "Microsoft",
"contact": "Bill Gates",
"id": 2,
"city": "Redmond"
},
{
"customer": "Microsoft",
"contact": "Satya Nadella",
"id": 3,
"city": "Redmond"
}
]
let selectedRow = customerTable
.filter(i => { return i.customer === selectedCustomer })
.filter(i => { return i.contact === selectedContact })
let id = selectedRow
.map(a => a.id)
.filter((item, pos, self) => {return self.indexOf(item) === pos}) // Remove duplicates
let city = selectedRow
.map(a => a.city)
.filter((item, pos, self) => { return self.indexOf(item) === pos })
是否有更高效的方法从这种类型的数据模型中选择多个值?
最佳答案
过滤器看起来不错;但是你可以filter with composing functions .
let id = [...selectedRow.reduce(
(result,item)=>result.add(item.id)
,new Set()
)]
或者正如 Jonas 指出的那样(所以你不需要 reduce):
let id = [...new Set(
selectedRow.map(item=>item.id)
)]
关于javascript - 选择表数据(对象数组)JS的高性能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56599058/