Ответ 1
Вы можете использовать Array.concat, как показано ниже: -
var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
var flattened = [].concat.apply([],arr);
flattened
будет вашим ожидаемым массивом.
У меня есть массив, который содержит несколько массивов, каждый из которых содержит несколько объектов, похожих на это.
[[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}]]
Вы можете использовать Array.concat, как показано ниже: -
var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
var flattened = [].concat.apply([],arr);
flattened
будет вашим ожидаемым массивом.
Рекурсивное решение для глубокого (вложенного) сглаживания:
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
принимает итератор (например, результаты от вызова функции генератора) и превращает его в массив.
Если вам нужно только простое выравнивание, это может сработать:
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];
Рекурсивно сгладить массив:
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
Использование ES6 Spread Operator
Array.prototype.concat(...searchData)
ИЛИ ЖЕ
[].concat(...searchData)
Я заметил, что люди используют рекурсии, которые не являются экономически выгодными, особенно с новыми стандартами 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]
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]
Вы можете использовать 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);