簡體   English   中英

JavaScript 展平 arrays 個對象的數組

[英]JavaScript flattening an array of arrays of objects

我有一個包含幾個 arrays 的數組,每個包含幾個對象,類似於此。

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

這是登錄到控制台的 object 的屏幕截圖。

將其展平的最佳方法是什么,因此它只是一組對象?

我試過這個沒有運氣:

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

您可以像下面這樣使用Array.concat :-

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

flattened將是您預期的數組。

ES 2020 將flatflatMap(如果您想迭代)提供給列表的平面列表:

[['object1'], ['object2']].flat() // ['object1', 'object2']

深度(嵌套)展平的遞歸解決方案:

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

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

我注意到人們正在使用成本不友好的遞歸,尤其是新的 ES6 標准賦予我們擴展運算符的力量。 當您將項目推入主陣列時,只需使用 ... 它會自動添加扁平對象。 就像是

array.push(...subarray1)    // subarray1 = [object1, object2]
array.push(...subarray2)    // subarray2 = [object3]
array.push(...subarray3)    // subarray3 = [object4,object5, object6]
// output -> array = [object1, object2, object3, object4, object5, object6]

您可以使用此自定義遞歸方法展平任何嵌套數組

const arr = [
  [1, 2],
  [3, 4, 5],
  [6, [7, 8], 9],
  [10, 11, 12]
]

const flatenedArray = arr => {
  let result = [];
  if(!arr.constructor === Array) return;
  arr.forEach(a => {
    if(a.constructor === Array) return result.push(...flatenedArray(a));
    result.push(a);
  });
  return result;
}


console.log(flatenedArray(arr)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

遞歸地展平一個數組:

 function flatten(array) { return !Array.isArray(array) ? array : [].concat.apply([], array.map(flatten)); } var yourFlattenedArray = flatten([[{"_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}]] ); log(yourFlattenedArray); function log(data) { document.write('<pre>' + JSON.stringify(data, null, 2) + '</pre><hr>'); }
 * {font-size: 12px; }

let functional = {
    flatten (array) {
        if (Array.isArray(array)) {
            return Array.prototype.concat(...array.map(this.flatten, this));
        }

        return array;
    }
};

functional.flatten([0, [1, 2], [[3, [4]]]]); // 0, 1, 2, 3, 4

我的解決方案是展平對象數組並返回單個數組。

flattenArrayOfObject = (arr) => {
  const flattened = {};

  arr.forEach((obj) => {
    Object.keys(obj).forEach((key) => {
      flattened[key] = obj[key];
    });
  });

  return flattened;
};

例子

const arr = [
  {
    verify: { '0': 'xyzNot verified', '1': 'xyzVerified' },
    role_id: { '1': 'xyzMember', '2': 'xyzAdmin' },
    two_factor_authentication: { '0': 'No', '1': 'Yes' }
  },
  { status: { '0': 'xyzInactive', '1': 'Active', '2': 'xyzSuspend' } }
]

flattenArrayOfObject(arr)

// {
//   verify: { '0': 'xyzNot verified', '1': 'xyzVerified' },
//   status: { '0': 'xyzInactive', '1': 'Active', '2': 'xyzSuspend' },
//   role_id: { '1': 'xyzMember', '2': 'xyzAdmin' },
//   two_factor_authentication: { '0': 'No', '1': 'Yes' }
// }

 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]

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]

如果每個對象都有一個數組並以相同的方式繼續嵌套:

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

]

 // 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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM