首页 > 解决方案 > 有没有办法从数组中取出对象并放入新数组中?

问题描述

鉴于:

myObjArray = [ [ [ [Object] ] ], [ [ [Object] ] ], [ [ [Object] ] ] ]

期望的结果

[{Object},{Object},{Object}]

那么有没有办法将 [Object(s)] 从数组中拉出并放入一个新数组中?

标签: javascriptnode.js

解决方案


array.prototype.map与从嵌套数组中检索对象的递归函数一起使用:

var arr = [ [ [ [ { prop: 'val1' }] ] ], [ [ [{ prop: 'val2' }] ] ], [ [ [{ prop: 'val3' }] ] ] ];

var res = arr.map(getObject);

function getObject(o) {
    return Array.isArray(o) ?  getObject(o[0]) : o;
}
console.log(res);


推荐阅读