简体   繁体   English

在javascript中循环两个数组

[英]Loop two arrays in javascript

I have a issue with two loops.我有两个循环的问题。

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

I want this :我要这个 :

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

Sorry I have edit the array对不起,我已经编辑了数组

I tried with a look with a loop with home.push(yellow) but the result is wrong.我试着用 home.push(yellow) 循环看看,但结果是错误的。

Can you help me ?你能帮助我吗 ?

Thanks谢谢

Try to do this尝试这样做

Assume the yellow array has only 1 item假设黄色数组只有 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]}
});

To Loop two array's and Assume the two arrays have the same length循环两个数组并假设两个数组具有相同的长度

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]}
});

Well, if your home value was correct, like:好吧,如果您的home价值是正确的,例如:

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

Then I believe what you're looking for would look like this:然后我相信你正在寻找的东西看起来像这样:

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