2017-03-18 35 views
0

ramdajs:項目定位與滿足內部數組給定的結構這樣的規格

[ 
    { 
    documentType: { id: 4001 } 
    correspondence: [ { id: 1000 }, { id: 1010 } ] 
    }, 
    { 
    documentType: { id: 102 } 
    correspondence: [ { id: 1000 } ] 
    }, 
    { 
    documentType: { id: 101 } 
    correspondence: [ { id: 1001 } ] 
    } 
] 

我試圖用ramda找到數組的索引,其中內對應數組包含1000

我已經試過這樣:

R.filter(R.where({ correspondence: R.any(R.where({ id: 1000 }))}))(data) 

回答

2

首先,你會想要一個輕微的調整,以您的謂詞函數,改變內R.whereR.propEq所有對一個恆定值,流量比較,而不是一個功能:使用R.reduce建立

一:

const pred = R.where({ correspondence: R.any(R.propEq('id', 1000))}) 

然後,我有你如何能接近兩個例子,都利用的R.addIndex捕獲指數列表而測試每個元件:使用R.map嵌入濾波之前在各元素的索引

const reduceWithIdx = R.addIndex(R.reduce) 
const fn = reduceWithIdx((acc, x, i) => pred(x) ? R.append(i, acc) : acc, []) 

fn(data) //=> [0, 1] 

第二種:

const mapWithIdx = R.addIndex(R.map) 

const fn = R.pipe(
    mapWithIdx(R.flip(R.assoc('idx'))), 
    R.filter(pred), 
    R.map(R.prop('idx')) 
) 

fn(data) //=> [0, 1] 
+0

shot chris,謝謝! – Jim

相關問題