[英]How do I convert an array object into a two-dimensional array
這是一個數組列表。
const list = [
{
id: 5844,
option: 'fruit'
children: ['apple', 'banana', 'pear']
},
{
id: 5845,
option: 'vegetables'
children: ['tomato', 'potato', 'spinach']
}
]
我想得到一個這樣的新數組
水果的孩子的蘋果是索引0
蔬菜的孩子的番茄指數= 0
所以他們是匹配的
[['apple', 'tomato'], ['banana', 'potato'], ['pear', 'spinach']]
我想我們可以試試這段代碼
const list = [
{
id: 5844,
option: 'fruit',
children: ['apple', 'banana', 'pear']
},
{
id: 5845,
option: 'vegetables',
children: ['tomato', 'potato', 'spinach']
}
]
var ans = []
list.forEach(item => {
item.children.forEach((child, index) => {
if (!ans[index]) {
ans[index] = []
ans[index].push(child)
} else {
ans[index].push(child)
}
})
})
使用此解決方案,數組中有多少對象並不重要。 您可以map
第一個對象中的子元素,並使用它的長度返回子元素的flatMap
。
const list=[{id:5844,option:"fruit",children:["apple","banana","pear"]},{id:5845,option:"vegetables",children:["tomato","potato","spinach"]},{id:5846,option:"buildings",children:["church","warehouse","skyscraper"]}]; function getNewData(list) { // `map` over the children in the first object // using its index to return a new flattened array // of all array object children return list[0].children.map((_, i) => { return list.flatMap(obj => obj.children[i]); }); } console.log(getNewData(list));
我假設你的孩子有相同的長度。 我們可以使用 2 循環對子元素進行分組。
第一個循環迭代子元素。
迭代列表元素的第二個循環。
這是解決您的案例的簡單代碼。
var listSize = list.length;
var childSize = list[0].children.length;
var expectedArrs = [];
for(var i=0;i<childSize;i++){
var groupByChild = [];
for(var j=0;j<listSize;j++){
groupByChild.push(list[j].children[i]);
}
expectedArrs.push(groupByChild);
}
console.log(expectedArrs);
控制台結果:
[["apple", "tomato"], ["banana", "potato"], ["pear", "spinach"]]
解決如下:
const result = []
for(let i = 0; i< List[0].children; i++){
const result1 = []
result1.push(list[0].children[i] )
result1.push(list[1].children[i])
result.push(result1)
}
var list = [ { id: 5844, option: 'fruit', children: ['apple', 'banana', 'pear'] }, { id: 5845, option: 'vegetables', children: ['tomato', 'potato', 'spinach'] } ] var newArr = []; var i=0; while(i<list.length){ newArr.push(list[i].children); i=i+1; } console.log(newArr)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.