web-dev-qa-db-ja.com

オブジェクトの配列の配列を平坦化するJavaScript

これに似た複数のオブジェクトを含む複数の配列を含む配列があります。

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

次のように Array.concat を使用できます:-

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

flattenedは予想される配列になります。

33
Mritunjay

深い(ネストされた)フラット化の再帰的ソリューション:

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;

楽しみのために、「flatten」に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は、イテレータ(ジェネレータ関数を呼び出した結果など)を受け取り、配列に変換します。

10
user663031

単純なフラット化のみが必要な場合、これは機能する可能性があります。

var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
var flatenned = arr.reduce(function(a,b){ return a.concat(b) }, []);

より複雑なフラット化のために、Lodashにはflatten機能があります。これはおそらく必要なものです。 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];
4
Huy Hoang Pham

ES6 Spread Operatorを使用

Array.prototype.concat(...searchData)

OR

[].concat(...searchData)

2
Shreyas

配列を再帰的にフラット化します。

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; }
2
Miguel Mota
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
2

特に、新しい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]
1
Adnan Khan

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);
0
Taki
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]
0
Gajender Singh
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
Tarun Majumder