JavaScript 展平对象数组的数组

IT技术 javascript arrays loops flatten
2021-02-22 00:55:50

我有一个数组,其中包含多个数组,每个数组包含多个对象,与此类似。

[[object1, object2],[object1],[object1,object2,object3]]

这是记录到控制台的对象的屏幕截图。

将其展平以便它只是一组对象的最佳方法是什么?

我试过这个没有运气:

console.log(searchData);  
  var m = [].concat.apply([],searchData);    
console.log(m);

searchData 登出上面的截图,但 m 登出 [ ]

这是searchData的实际内容:

[[{"_id":"55064111d06b96d974937a6f","title":"Generic Title","shortname":"generic-title","contents":"<p>The Healing Center offers practical, social, and spiritual support to individuals and families. Services include, but are not limited to: food and clothing, job skills training and job search assistance, auto repair (Saturdays only), mentoring, financial counseling, tutoring, prayer, life skills training, and helpful information about local community services.</p><p>Stay in touch with us:</p>","__v":0},{"_id":"5508e1405c621d4aad2d2969","title":"test english","shortname":"test-page","contents":"<h2>English Test</h2>","__v":0}],[{"_id":"550b336f33a326aaee84f883","shortname":"ok-url","title":"now english","contents":"<p>okokko</p>","category":"Transportation","__v":0}]]
6个回答

您可以像下面这样使用Array.concat:-

var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
var flattened = [].concat.apply([],arr);

flattened 将是您预期的数组。

ES 2020 提供了flat如果你想迭代,还提供flatMap到列表的平面列表:

[['object1'], ['object2']].flat() // ['object1', 'object2']
@Mritunjay 你能在你的代码中添加解释吗?
2021-04-16 00:55:50
出于某种原因,这将返回一个空数组。任何想法为什么可能会发生?
2021-04-17 00:55:50
@byrdr 你能发布一下你到底在尝试什么吗?
2021-05-01 00:55:50
它适用于答案中提供的数组。但出于某种原因,我的数组返回 []。
2021-05-03 00:55:50
我比我的减少答案更喜欢这个。
2021-05-12 00:55:50

深度(嵌套)展平的递归解决方案:

function flatten(a) {
  return Array.isArray(a) ? [].concat.apply([], a.map(flatten)) : a;
}

使用 ES6 更紧凑一点:

var flatten = a => Array.isArray(a) ? [].concat(...a.map(flatten)) : a;

为了好玩,使用一个以F“flatten”命名的生成器,懒惰地生成扁平化的值:

function *F(a) {
  if (Array.isArray(a)) for (var e of a) yield *F(e); else yield a;
}

>> console.log(Array.from(F([1, [2], 3])));
<< [ 1, 2, 3 ]

对于那些不熟悉生成器的人来说,yield *语法从另一个生成器产生值。Array.from获取一个迭代器(例如调用生成器函数的结果)并将其转换为数组。

如果您只需要简单的展平,这可能有效:

var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
var flatenned = arr.reduce(function(a,b){ return a.concat(b) }, []);

对于更复杂的展平,Lodash 有展平功能,这可能是你需要的:https ://lodash.com/docs#flatten

//Syntax: _.flatten(array, [isDeep])

_.flatten([1, [2, 3, [4]]]);
// → [1, 2, 3, [4]];

// using `isDeep` to recursive flatten
_.flatten([1, [2, 3, [4]]], true);
// → [1, 2, 3, 4];
@dandavis 好吧,他需要做的就是指定可​​选参数_.flatten以获取深层行为,或者调用_.flattenDeep.
2021-04-20 00:55:50
展示为什么更喜欢 [].reduce 与 _.flatten 的好例子!
2021-04-22 00:55:50
OP 没有询问 lodash。Lodash 的答案对关于语言本身的问题没有帮助,而且许多人不希望语言已经做了一些额外的依赖,没有它。
2021-05-11 00:55:50

使用 ES6 扩展运算符

Array.prototype.concat(...searchData)

或者

[].concat(...searchData)

你可以使用flat()

const data = [ [{id:1}, {id:2}], [{id:3}] ];
const result = data.flat();
console.log(result);

// you can specify the depth

const data2 = [ [ [ {id:1} ], {id:2}], [{id:3}] ];
const result2 = data2.flat(2);

console.log(result2);

在你的情况下:

const data = [[{"_id":"55064111d06b96d974937a6f","title":"Generic Title","shortname":"generic-title","contents":"<p>The Healing Center offers practical, social, and spiritual support to individuals and families. Services include, but are not limited to: food and clothing, job skills training and job search assistance, auto repair (Saturdays only), mentoring, financial counseling, tutoring, prayer, life skills training, and helpful information about local community services.</p><p>Stay in touch with us:</p>","__v":0},{"_id":"5508e1405c621d4aad2d2969","title":"test english","shortname":"test-page","contents":"<h2>English Test</h2>","__v":0}],[{"_id":"550b336f33a326aaee84f883","shortname":"ok-url","title":"now english","contents":"<p>okokko</p>","category":"Transportation","__v":0}]]

const result = data.flat();

console.log(result);