JavaScript 数组扁平化:将一个包含对象的数组嵌套多层的数组转换为一维数组

56

我有一个包含多个数组的数组,每个数组中包含多个对象,类似于这样。

[[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}]]

11
我喜欢 arr.reduce(function(a,b){return a.concat(b);}); 这行代码。 - dandavis
1
由于某种原因,它给了我一个空的 [ ]。我尝试过其他几种方法,但也没有成功...我不确定为什么? - byrdr
2
如果所有提供的选项都无法正常工作,那么您肯定是在做其他错误的事情。 - dandavis
你能把searchData的内容也发布一下吗? - Mritunjay
要将深度嵌套的对象数组展平,您需要使用递归。请查看此文章获取解决方案。 - Talha Awan
显示剩余2条评论
14个回答

1
如果每个对象都有一个数组,并以相同的方式嵌套:
function flatten(i,arrayField){
  if(Array.isArray(i)) return i.map(c=>flatten(c,arrayField));
  if(i.hasOwnProperty(arrayField)) return [{...i,[arrayField]:null},...i[arrayField].map(c=>flatten(c,arrayField))];
  return {...i,[arrayField]:null};
}

let data=flatten(myData,'childs');

我的数据如下:

[
{
    "id": 1,
    "title": "t1",
    "sort_order": 200,
    "childs": [
        {
            "id": 2,
            "title": "t2",
            "sort_order": 200,
            "childs": []
        },
        {
            "id": 3,
            "title":"mytitle",
            "sort_order": 200,
            "childs": []
        },
        {
            "id": 4,
            "title":"mytitle",
            "sort_order": 200,
            "childs": []
        },
        {
            "id": 5,
            "title":"mytitle",
            "sort_order": 200,
            "childs": []
        },
        {
            "id": 6,
            "title":"mytitle",
            "sort_order": 200,
            "childs": []
        }
    ]
},
{
    "id": 7,
    "title": "راهنما",
    "sort_order":"mytitle",
    "childs": [
        {
            "id": 8,
            "title":"mytitle",
            "sort_order": 200,
            "childs": []
        },
        {
            "id": 9,
            "title":"mytitle",
            "sort_order": 200,
            "childs": []
        },
        {
            "id": 10,
            "title":"mytitle",
            "sort_order": 200,
            "childs": []
        }
    ]
}

]


0

let nestedArray = [[1, 2], [3, 4], [5, 6]];

let flattenArray = function(nestedArray) {

 let flattenArr = [];
  
 nestedArray.forEach(function(item) {
   flattenArr.push(...item);
  });
  
  return flattenArr;
};

console.log(flattenArray(nestedArray)); // [1, 2, 3, 4, 5, 6]


0

// Polyfill flat method

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

var deepFlatten = (arr, depth = 1) => {
   return depth > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? deepFlatten(val, depth - 1) : val), [])
                : arr.slice();
}

console.log(deepFlatten([0, 1, 2, [[[3, 4]]]], Infinity));

// You can pass label in place of 'Infinity'


0
var arr = [1,[9,22],[[3]]];
var res = [];

function flatten(arr){
for(let i=0;i<arr.length;i++){
if(typeof arr[i] == "number"){
res.push(arr[i]);
}
else if(typeof arr[i] == "object"){
fatten(arr[i]);
}
}
}

调用函数

flatten(arr);
console.log(res);

结果

[1, 9, 22, 3]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接