recorrer - JavaScript allanando una matriz de matrices de objetos
matriz javascript (10)
Tengo una matriz que contiene varias matrices, cada una con varios objetos, similar a esto.
[[object1, object2],[object1],[object1,object2,object3]]
Aquí hay una captura de pantalla del objeto registrado en la consola.
¿Cuál sería el mejor enfoque para aplanar esto, por lo que es solo una serie de objetos?
He intentado esto sin suerte:
console.log(searchData);
var m = [].concat.apply([],searchData);
console.log(m);
searchData cierra la captura de pantalla anterior, pero m cierra la sesión []
Aquí está el contenido real de 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}]]
Uso del operador de propagación ES6
Array.prototype.concat(...searchData)
O
[].concat(...searchData)
Aplanar recursivamente una matriz:
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; }
Me he dado cuenta de que las personas usan recurrencias que no son rentables, especialmente con los nuevos estándares ES6 que nos dan el poder de los operadores de propagación. Cuando empuje los elementos a la matriz maestra, simplemente use ... y agregará automáticamente objetos aplanados. Algo como
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]
Puede usar Array.concat como a continuación: -
var arr = [[''object1'', ''object2''],[''object1''],[''object1'',''object2'',''object3'']];
var flattened = [].concat.apply([],arr);
flattened
será su matriz esperada.
Si solo necesita aplanar simple, esto puede funcionar:
var arr = [[''object1'', ''object2''],[''object1''],[''object1'',''object2'',''object3'']];
var flatenned = arr.reduce(function(a,b){ return a.concat(b) }, []);
Para un aplanamiento más complejo, Lodash tiene la función de aplanamiento, que tal vez sea lo que necesita: 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];
Una solución recursiva para el aplanamiento profundo (anidado):
function flatten(a) {
return Array.isArray(a) ? [].concat.apply([], a.map(flatten)) : a;
}
Un poco más compacto con ES6:
var flatten = a => Array.isArray(a) ? [].concat(...a.map(flatten)) : a;
Por diversión, usando un generador llamado
F
para "aplanar", para generar perezosamente valores aplanados:
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 ]
Para aquellos que no están familiarizados con los generadores, la sintaxis
yield *
arroja valores de otro generador.
Array.from
toma un iterador (como los resultados de invocar la función del generador) y lo convierte en una matriz.
puedes usar 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);
en tu caso :
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);
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]
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
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]);
}
}
}
Función de llamada
flatten(arr);
console.log(res);
Resultado
[1, 9, 22, 3]