简体   繁体   English

如何使用 ramda 获取对象中的所有值

[英]How do you get all the value in an object using ramda

how do you map to all the object and get all the value using ramda你如何映射到所有对象并使用 ramda 获取所有值

const input ={
  a: 'apple',
  b:{
    c:{
      d:{
        e: 'egg',
        f: 'fish'
      }
    },
    g: 'guava',
    h: 'honey',
  }
}

console.log :控制台日志:

['apple',
'egg',
'fish',
'guava',
'honey']

You can use Object.values() , and Array.flatMap() to create a recursive function that gets the values from an object, and then iterates the values, and calls itself on every value that is an object:您可以使用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)

You can create a pointfree function with Ramda, that does the same thing:你可以用 Ramda 创建一个 pointfree 函数,它做同样的事情:

  1. Get the values,获取值,
  2. Use R.When with R.is(Object) to check if the value is an object, and call getDeepValues on the value if it is (the arrow function is needed because the getDeepValues is not declared yet), or return the value if it's not.使用 R.When 和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>

No need to use Ramda, you can do it in plan JS in one cleverly-written recursive reduce :无需使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM