JavaScript展平对象数组的数组

时间:2015-03-20 03:07:39

标签: javascript arrays loops flatten

我有一个包含多个数组的数组,每个数组包含几个对象,类似于此。

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

12 个答案:

答案 0 :(得分:37)

您可以使用下面的Array.concat: -

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

flattened将是您预期的数组。

答案 1 :(得分:11)

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

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的生成器进行“展平”,懒洋洋地生成扁平值:

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接受一个迭代器(例如调用生成器函数的结果)并将其转换为数组。

答案 2 :(得分:4)

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

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

答案 3 :(得分:2)

递归展平数组:

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

答案 4 :(得分:2)

std::string

答案 5 :(得分:2)

  

使用ES6 Spread Operator

Array.prototype.concat(...searchData)

OR

[].concat(...searchData)

答案 6 :(得分:1)

我注意到人们正在使用成本低廉的递归,特别是在新的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]

答案 7 :(得分:1)

我将对象数组展平并返回单个数组的解决方案。

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

flattenObject(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' }
// }

答案 8 :(得分: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]

答案 9 :(得分: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]

答案 10 :(得分:0)

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

答案 11 :(得分:0)

如果每个对象都有一个数组并以相同的方式继续嵌套:

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

]