gpt4 book ai didi

javascript - 数组映射和缩减显示未定义的值

转载 作者:行者123 更新时间:2023-12-04 07:38:23 24 4
gpt4 key购买 nike

我有两个名为 headersMap 的数组和 selected_arr如下

headersMap: [
{
text: "#",
align: "center",
sortable: true,
value: "id",
align: "start",
width: "1%",
},
{
text: "Name",
align: "center",
sortable: true,
value: "name",
align: "start",
},
{
text: "Company",
align: "center",
sortable: true,
value: "company",
align: "start",
}
]
selected_arr: ['id', 'company']
我尝试过的内容如下:
let jsonObject = this.headersMap;
let selectedArray = this.selected_arr;
let filteredJsonObject = jsonObject.map(function(entry) {
return selectedArray.reduce(function(res, key) {
res[key] = entry[key];
return res;
}, {});
});

console.log(filteredJsonObject);
输出:
[
{
#: undefined
company: undefined
}
]
问题:我想要的是减少 headersMap来自 selected_arr ,输出应如下所示:
[
{
text: "#",
align: "center",
sortable: true,
value: "id",
align: "start",
width: "1%",
},
{
text: "Company",
align: "center",
sortable: true,
value: "company",
align: "start",
}
]

最佳答案

使用 Array#filter :

const 
headersMap = [
{ text: "#", align: "center", sortable: true, value: "id", align: "start", width: "1%" },
{ text: "Name", align: "center", sortable: true, value: "name", align: "start" },
{ text: "Company", align: "center", sortable: true, value: "company", align: "start" }
],
selected_arr = ['id', 'company'];

const filtered = headersMap.filter(({ value }) => selected_arr.includes(value));

console.log(filtered);

关于javascript - 数组映射和缩减显示未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67627504/

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