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

时间:2018-09-07 07:29:10

标签: javascript arrays object underscore.js

有人可以帮我吗?我花了很长时间试图弄清楚。我有以下格式:

[
  [{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'}, ...]
]

以这种格式(最好是._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'}

3 个答案:

答案 0 :(得分:2)

您的问题还不够清楚,但是如果您只想展平数组,则可以使用以下代码:

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

答案 1 :(得分:1)

我不确定您到底想要什么,但是您可以尝试使用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>

答案 2 :(得分:0)

您可以使用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>