這是一個陣列串列。
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']]
uj5u.com熱心網友回復:
我想我們可以試試這段代碼
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)
}
})
})
uj5u.com熱心網友回復:
使用此解決方案,陣列中有多少物件并不重要。您可以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));
uj5u.com熱心網友回復:
我假設你的孩子有相同的長度。我們可以使用 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"]]
uj5u.com熱心網友回復:
解決如下:
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)
}
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/335895.html
標籤:javascript 算法 数据结构
