gpt4 book ai didi

javascript - 使用自动索引在循环中创建多维数组

转载 作者:行者123 更新时间:2023-12-01 08:29:38 26 4
gpt4 key购买 nike

我想使用 jQuery/JS 中的循环创建一个多维数组。是否可以使用下一个可用的 key 而不是手动设置?

jsonFromPhp 包含如下内容:

0 {first_name: "Tom", last_name: "Smith", location: "London"}
1 {first_name: "Max", last_name: "Muster", location: "Zurich"}
2 {first_name: "Joanne", last_name: "Kate", location: "London"}
...

这是循环:

jsonFromPhp.forEach((row, i) => {
if (row['location'] == 'London') {
firstKey = 0;
} else {
   firstKey = 1;
}

row.forEach((singleData, n) => {
pushedArray[firstKey][] = singleData[n]; // doesn't work, I have set the index manually (with i for example). But then I have an array like 0, 2, 5 etc. and I need 0, 1, 2
});
});

Expected Result:
0 Array (1)
0 ["Tom", "Smith", "London"] (3)
1 ["Joanne", "Kate", "London"] (3)
...
1 Array (1)
0 ["Max", "Muster", "Zurich"] (3)
...

而不是(如果我设置 PushArray[firstKey][i])

0 Array (1)
0 ["Tom", "Smith", "London"] (3)
2 ["Joanne", "Kate", "London"] (3)
...
1 Array (1)
1 ["Max", "Muster", "Zurich"] (3)
...

0 Array (1)
0 ["Tom", "Smith", "London", "Joanne", "Kate", "London"] (6)
1 Array (1)
1 ["Max", "Muster", "Zurich"] (3)
...

最佳答案

use the next available key

要自动生成数组索引,最简单的方法是使用

arr.push(value)

这与

相同
arr[arr.length] = value

这个问题的问题是多维数组,以确保您“插入”正确的维度。

在本例中,第一个维度(“伦敦”)的长度始终为 2,因此我们可以通过预先创建数组来简化这一点:

var arr = [[],[]];

它创建一个包含 2 个条目的数组,这两个条目本身都是空数组(二维)。

然后代码确定是使用 0 还是 1,这很好 - 下一个维度是源中的每一行/对象,在该维度下是数据所在的位置,给出:

var source = [
{first_name: "Tom", last_name: "Smith", location: "London"},
{first_name: "Max", last_name: "Muster", location: "Zurich"},
{first_name: "Joanne", last_name: "Kate", location: "London"}
];

// create 1st dimension (arr[0], arr[1]) initially
var arr=[[],[]];

// loop through each source row
source.forEach((row, i) => {
if (row['location'] == 'London') {
firstKey = 0;
} else {
firstKey = 1;
}

// add a subdimension for this row
var rowArr = [];
for(var k in row)
{
// add the properties into the subdimension
rowArr.push(row[k]);
}

// add the object->array into the 0/1 top-level array
// using "the next available index"
arr[firstKey].push(rowArr);

});
console.log(arr);

这可以或当然可以大大减少(例如使用 .map?: 作为位置),但这会保持最接近原始代码,仅更改部分与问题相关。

<小时/>

使用 .forEach 减少代码

使用object to array与预先创建基本数组的原理相同,您可以使用 ?: 来减少位置索引:

firstKey = row['location'] == 'London' ? 0 : 1

我们可以将您的代码简化为一行代码(为了清晰起见,将其拆分):

var source = [
{first_name: "Tom", last_name: "Smith", location: "London"},
{first_name: "Max", last_name: "Muster", location: "Zurich"},
{first_name: "Joanne", last_name: "Kate", location: "London"}
];

var arr = [[],[]];

source.forEach((row) =>
arr[row['location'] == 'London' ? 0 : 1].push(
Object.keys(row).map(
(key) => row[key]
)
)
);

console.log(arr)

关于javascript - 使用自动索引在循环中创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61930789/

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