gpt4 book ai didi

javascript - 选择表数据(对象数组)JS的高性能方法

转载 作者:行者123 更新时间:2023-11-30 11:03:37 25 4
gpt4 key购买 nike

我正在尝试优化从大表(对象数组)中选择数据。

我想从一行中保存多个值,然后写入 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 .

获取唯一值可以使用 Set 进行优化和 reduce :

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com