簡體   English   中英

如何使用 Ramda 表達式將包含 arrays 對象的數組轉換為帶有軟管 object 的單個數組?

[英]How to convert an array containing arrays of objects to single array witht hose object using Ramda expressions?

我遇到了困難,我的代碼上有一些不好的映射。

我有一個包含這樣的對象數組的數組:

[
   [{a: 1, b: 2},{a: 1, b: 3} ],
   [{a: 5, b: 2},{a: 2, b: 5}]
]

我想這樣做:

[
   {a: 1, b: 2},
   {a: 1, b: 3},
   {a: 5, b: 2},
   {a: 2, b: 5}
]

為了做到這一點,我想我找到了神奇的解決方案,讓事情變平,使用flatten function,它不起作用(這個問題只是很多代碼中的一段代碼)我想知道為什么,我浪費了一些是時候發現這個問題了,這不是我所期望的行為,正如您在圖像中看到的那樣,我擁有的第一件事是一個數組,其中包含一個具有兩個對象的數組,使用flatten方法,我期待一個數組兩個對象,但我得到了您在圖像中看到的內容:

在此處輸入圖像描述

我試過的代碼是這樣的:

const expectedArray = R.flatten(myArrayOfArraysOfObjects);

完整示例:

const singleTronconPoints = troncon => {
  return troncon.geometri_linestring;
};
console.log('troncons : ');
console.log(troncons);
console.log('map troncons points');
console.log(map(singleTronconPoints, troncons));
console.log('flatten');
console.log(flatten(map(singleTronconPoints, troncons)));

這是完整的結果: 在此處輸入圖像描述

我該如何解決,是否有另一個神奇的 (:P) 解決方案 ( method ) 來解決這個問題?

任何幫助將非常感激。

Array.prototype.reduce()也可以是一個選項:

const arr =[
  [{a: 1, b: 2},{a: 1, b: 3}],
  [{a: 5, b: 2},{a: 2, b: 5}]
]

const expectedArray = arr.reduce((acc, array) => {
  acc.push(...array);
  return acc;
}, []);

您可以使用array.flat

 let a = [ [{ a: 1, b: 2 }, { a: 1, b: 3 }], [{ a: 5, b: 2 }, { a: 2, b: 5 }] ]; let b = a.flat(); console.log(b)

或者,您可以使用reduce和內部回調使用forEach並將嵌套數組中的項目放入累加器數組

 let a = [ [{ a: 1, b: 2 }, { a: 1, b: 3 }], [{ a: 5, b: 2 }, { a: 2, b: 5 }] ]; let b = a.reduce((acc, curr) => { curr.forEach(item => acc.push(item)) return acc; }, []); console.log(b)

使用reduce() + push 哪個更快的flat()方法。

參考這個來檢查性能。 : https://jsbench.me/0ikcqa83ck/1

 let arr = [ [{a: 1, b: 2},{a: 1, b: 3} ], [{a: 5, b: 2},{a: 2, b: 5}] ] console.log(arr.flat()) let flattenArr = arr.reduce((acc, val) => (acc.push(...val),acc), []) console.log(flattenArr);

Array.flat是您正在尋找的神奇解決方案!

 var arr = [ [{a: 1, b: 2},{a: 1, b: 3} ], [{a: 5, b: 2},{a: 2, b: 5}] ] console.log(arr.flat())

暫無
暫無

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

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