我想使用jQuery / JS中的循环创建多维数组。是否可以使用下一个可用键代替手动设置?
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)
...
此解决方案将在2个以上的位置工作,并且无需关心后端location
的值是什么。
const arr = [{
first_name: "Tom",
last_name: "Smith",
location: "London"
}, {
first_name: "Max",
last_name: "Muster",
location: "Zurich"
}, {
first_name: "Joanne",
last_name: "Kate",
location: "London"
}]
const result = {};
arr.map(item => {
result[item.location] = [];
return item;
}).map(item => {
result[item.location].push(Object.values(item));
});
let res2 = [];
Object.keys(result).forEach((key, index) => {
res2[index] = result[key]
});
console.log(res2)
使用下一个可用键
要自动生成数组索引,最简单的方法是使用
arr.push(value)
与]相同>
arr[arr.length] = value
此问题的问题在于多维数组,以确保您将“推入”到正确的维中。
在这种情况下,第一维(“伦敦”)始终为2长,因此我们可以通过预先创建数组来简化此操作:
var arr = [[],[]];
将创建一个包含2个条目的数组,它们本身都是空数组(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
和?:
作为位置),但这会保持最接近原始代码的位置,只更改与问题相关的部分。