简体   繁体   English

如何合并包含相同对象键的多个子数组?

[英]how to combine multiple sub-arrays that contain same objects' keys?

Can someone help me with this, please? 有人可以帮我吗? I've spent a long time trying to figure it out. 我花了很长时间试图弄清楚。 I have the following format: 我有以下格式:

[
  [{id:'1',venue:'foa',title:'t'},{id:'5',venue:'cs',title:'b'}, ...],
  [{id:'2',venue:'fob',title:'t'},{id:'6',venue:'cs',title:'b'}, ...],    
  [{id:'3',venue:'foc',title:'t'},{id:'7',venue:'cs',title:'b'}, ...],
  [{id:'4',venue:'fod',title:'t'},{id:'8',venue:'cs',title:'b'}, ...]
]

what is the simplest way to make it in this format (._underscore preferably): 以这种格式(最好是._underscore)制作它的最简单方法是:

{id:'1',venue:'foa',title:'t'}
{id:'5',venue:'cs',title:'b'}
{id:'2',venue:'fob',title:'t'}
{id:'6',venue:'cs',title:'b'}
{id:'3',venue:'foc',title:'t'}
{id:'7',venue:'cs',title:'b'}
{id:'4',venue:'fod',title:'t'}
{id:'8',venue:'cs',title:'b'}

Your question is not clear enough but if you just want to flatten your array, you can use the below code: 您的问题还不够清楚,但是如果您只想展平数组,则可以使用以下代码:

 var arr = [ [{id:'1',venue:'foa',title:'t'},{id:'5',venue:'cs',title:'b'}], [{id:'2',venue:'fob',title:'t'},{id:'6',venue:'cs',title:'b'}], [{id:'3',venue:'foc',title:'t'},{id:'7',venue:'cs',title:'b'}], [{id:'4',venue:'fod',title:'t'},{id:'8',venue:'cs',title:'b'}] ]; var res = [].concat(...arr); console.log(res); 

I'm not sure what exactly you want but here's what you can try using Lodash: 我不确定您到底想要什么,但是您可以尝试使用Lodash:

 var result = []; var obj = [ [{id:'1',venue:'foa',title:'t'},{id:'5',venue:'cs',title:'b'}], [{id:'2',venue:'fob',title:'t'},{id:'6',venue:'cs',title:'b'}], [{id:'3',venue:'foc',title:'t'},{id:'7',venue:'cs',title:'b'}], [{id:'4',venue:'fod',title:'t'},{id:'8',venue:'cs',title:'b'}] ]; _.each(obj, function(i) { _.each(i, function(j) { result.push(j); }); }); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script> 

You can use flatten() . 您可以使用flatten()

 var arr = [[{id:'1',venue:'foa',title:'t'},{id:'5',venue:'cs',title:'b'}],[{id:'2',venue:'fob',title:'t'},{id:'6',venue:'cs',title:'b'}], [{id:'3',venue:'foc',title:'t'},{id:'7',venue:'cs',title:'b'}],[{id:'4',venue:'fod',title:'t'},{id:'8',venue:'cs',title:'b'}]], result = _.flatten(arr); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM