[英]How do you get all the value in an object using ramda
你如何映射到所有對象並使用 ramda 獲取所有值
const input ={
a: 'apple',
b:{
c:{
d:{
e: 'egg',
f: 'fish'
}
},
g: 'guava',
h: 'honey',
}
}
控制台日志:
['apple',
'egg',
'fish',
'guava',
'honey']
您可以使用Object.values()
和Array.flatMap()
來創建一個遞歸函數,該函數從對象中獲取值,然后迭代這些值,並在作為對象的每個值上調用自身:
const getDeepValues = obj => Object .values(obj) .flatMap(v => typeof v === 'object' ? getDeepValues(v) : v) const input = {"a":"apple","b":{"c":{"d":{"e":"egg","f":"fish"}},"g":"guava","h":"honey"}} const result = getDeepValues(input) console.log(result)
你可以用 Ramda 創建一個 pointfree 函數,它做同樣的事情:
R.is(Object)
檢查值是否為對象,如果是則調用getDeepValues
值(需要箭頭函數,因為尚未聲明getDeepValues
),如果是則返回值不是。 const { pipe, values, chain, when, is } = R const getDeepValues = pipe( values, // get the values chain(when(is(Object), v => getDeepValues(v))) // if the value is an object use getDeepValues or just return the value ) const input = {"a":"apple","b":{"c":{"d":{"e":"egg","f":"fish"}},"g":"guava","h":"honey"}} const result = getDeepValues(input) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
無需使用 Ramda,您可以在計划 JS 中通過一個巧妙編寫的遞歸減少來實現:
const getDeepValues = obj => Object .values(obj) // 1. iterate over the object values .reduce((acc, cur) => [ ...acc, // 3. pass previous values ...( cur instanceof Object // 4. if the value we encounter is an object... ? getDeepValues(cur) // ...then use recursion to add all deep values : [cur] // ...else add one string ), ], []); // 2. start with an empty array const input ={ a: 'apple', b:{ c:{ d:{ e: 'egg', f: 'fish' } }, g: 'guava', h: 'honey', } } console.log(getDeepValues(input))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.