簡體   English   中英

在javascript中循環兩個數組

[英]Loop two arrays in javascript

我有兩個循環的問題。

yellow=[
         {
          beta: {
               id: '25',
               name: 'tata'
           }
         }
        ]
home=[
       {
          house : [
          {
             title: 'alpha',
             name : 'Vik',
          },
          {
             title: 'alpha1',
             name : 'Vik1',
          },
        ]
      }]

我要這個 :

villa=[
        {
            beta:{ 
            id: 'toto', name: 'tata'
            },
          title: 'alpha',
          name : 'Vik'
        },
        {
            beta:{ 
            id: 'toto', name: 'tata'
            },
          title: 'alpha1',
          name : 'Vik1'
        }
      }
     ]

對不起,我已經編輯了數組

我試着用 home.push(yellow) 循環看看,但結果是錯誤的。

你能幫助我嗎 ?

謝謝

嘗試這樣做

假設黃色數組只有 1 項

const yellow=[{beta: {id: '25', name: 'tata'}}];
const home=[{title: 'alpha', name : 'Vik'},
 {'alpha1', name : 'Vik1'} ];

// Assume the yellow array has only 1 item
const result = home.map((item)=>{
  return {...item,...yellow[0]}
});

循環兩個數組並假設兩個數組具有相同的長度

const yellow=[{beta: {id: '25', name: 'tata'}}];
const home=[{title: 'alpha', name : 'Vik'},
 {'alpha1', name : 'Vik1'} ];

// Assume the yellow array has only 1 item
const result = home.map((item,index)=>{
  return {...item,...yellow[index]}
});

好吧,如果您的home價值是正確的,例如:

yellow = [{beta: {id: '25', name: 'tata'}}];
home = [{title: 'alpha', name : 'Vik'},{title: 'alpha1', name : 'Vik1'}];

然后我相信你正在尋找的東西看起來像這樣:

home.reduce((res, h) => {
    yellow.forEach(y => {
        h.beta = y.beta;
        res.push(h)
    });
    return res;
}, []);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM