所以我有这个问题。
我有这个包含3个数组的对象......
items = {
a: ['STRAWBERRY', 'PEANUT'],
b: ['John', 'Doe', 'Scarface'],
c: ['Circle', 'Square', 'Triangle', 'Rectangle'],
}
我需要这个输出:
[
'STRAWBERRY',
'John',
'Circle',
'PEANUT',
'Doe',
'Square',
'Scarface',
'Triangle',
'Rectangle'
]
请注意,输出在“物品”的每个阵列的各个值之间交错。对象
我试图想出一个很好的方法去做那种"合并"但是我只能用巨大的方法和大量的代码来思考。
有快速优化的方法吗?
P.S。:我可以使用任何框架。
修改 使用@evillive回答我能够适应我在Coffee Script中的代码
使用COFFEE SCRIPT解决
result = []
col = -1
loop
col++
run = false
for k of Items
Items[k][col] and (run = result.push(Items[k][col]))
unless run
break
console.log result
答案 0 :(得分:1)
要保留该订单,您可以执行以下操作:http://jsfiddle.net/o5k965ze/
var items = {
a: ['STRAWBERRY', 'PEANUT'],
b: ['John', 'Doe', 'Scarface'],
c: ['Circle', 'Square', 'Triangle', 'Rectangle'],
};
function getLength (obj) {
var length = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key].length > length) {
length = obj[key].length;
}
}
}
return length;
}
function merge () {
var newArray = [];
var length = getLength(items);
console.log(length);
var index = 0;
for ( ; index < length; index++) {
for (var key in items) {
if (items[key][index]) {
newArray.push(items[key][index]);
}
}
}
console.log(newArray)
}
merge();
这将为您提供所需的订单,并且应该可以在该对象中使用3个以上的数组。
答案 1 :(得分:0)
使用lodash可以简化:
_.flattenDeep(_.values(items));
答案 2 :(得分:0)
{
xtype: 'actioncolumn',
tooltip: this.self.QUICKLOOK_TOOLTIP,
tdCls: 'action-column',
isDisabled: function(view, rowIndex, colIndex, item, record) {
return !this.quicklookable(record);
},
getClass: function(value, metaData, record) {
return this.quicklookable(record) ? 'bui-icon quicklook' : '';
},
itemId: 'activityListOpenQuicklook',
width: 50,
align: 'center',
handler: function(grid, rowIndex, colIndex, item, evt, record, row) {
this.fireEvent('openQuicklook', record);
},
scope: this
}
答案 3 :(得分:0)
无需查找最大长度参数。
var result = [];
while(Object.getOwnPropertyNames(items).length){
for(var k in items){
result.push(items[k].shift());
if (items[k].length == 0) delete items[k];
}
}
<强>更新强>
遗憾的是,shift
和delete
指令使以前的代码在性能方面不足。所以我重新编写它以使其更快。
var result = [], col = -1, run;
do {
col++; run = false;
for(var k in items){
items[k][col] && (run = result.push(items[k][col]))
}
} while(run)