gpt4 book ai didi

javascript - 如何将元素插入到javascript中二维数组的特定索引中?

转载 作者:行者123 更新时间:2023-12-05 00:31:50 24 4
gpt4 key购买 nike

我有一个如下所示的对象

const tableData = [
{

"Location": "London",
"Status": "Unknown"
},
{

"Location": "Delhi",
"Status": "Reachable"
},
{

"Location": "Berlin",
"Status": "Unknown"
},
{

"Location": "Tokyo",
"Status": "Busy"
},
]
现在我想创建一个二维数组,它将以某种方式保存这些信息。这是我下面的代码
const statusOrder = {"Reachable": 0, "Busy": 1, "Unknown": 2}
let statusOrderInfo = Array(Object.keys(statusOrder).length).fill([]);
for(let i=0; i< tableData.length; i++) {
const status = tableData[i]["Status"].trim()
const statusIndex = statusOrder[status]
statusOrderInfo[statusIndex].push(tableData[i])
}
console.log(statusOrderInfo)
如您所见,我想要 tableData 的每个项目对象位于二维数组的某个索引中。所以包含 Status 的项目如 Reachable应该在索引 0 处,即包含 Status 的项目如 Busy应该在索引 1 处,依此类推。
所以最终的输出应该看起来像
[
[
{
"Location":"Delhi",
"Status":"Reachable"
}
],
[
{
"Location":"Tokyo",
"Status":"Busy"
}
],
[
{
"Location":"London",
"Status":"Unknown"
},
{
"Location":"Berlin",
"Status":"Unknown"
}
]
]
但是即使我的目标是正确的索引,我在运行上述代码时也会得到错误的输出。我的方法有什么问题?

最佳答案

使用 Array#reduce :

const 
tableData = [ { "Location": "London", "Status": "Unknown" }, { "Location": "Delhi", "Status": "Reachable" }, { "Location": "Berlin", "Status": "Unknown" }, { "Location": "Tokyo", "Status": "Busy" } ],
statusOrder = {"Reachable": 0, "Busy": 1, "Unknown": 2};

const statusOrderInfo = tableData.reduce((list, e) => {
const index = statusOrder[e.Status];
list[index] = [...(list[index] || []), {...e}];
return list;
}, []);

console.log(statusOrderInfo);

关于javascript - 如何将元素插入到javascript中二维数组的特定索引中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70478695/

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