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

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',
  }
}

console.log :

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

不需要使用Ramda,你可以在plan JS中用一个聪明的递归实现reduce:

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))

您可以使用 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 函数,做同样的事情:

  1. 获取值,
  2. 使用 R.When 和 R.is(Object) 检查值是否是对象,如果是则调用 getDeepValues (需要箭头函数,因为 getDeepValues 尚未声明),或 return 如果未声明则为值。

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>