Ramda: find object key by nested key value

笑着哭i 提交于 2020-07-22 21:50:23

问题


Is there any function in ramda how can I find key by nested key value? I found a way how to find an object in array but that doesn't help. I need something like this:

const obj = {
  addCompany: {
    mutationId: '1'
  },
  addUser: {
    mutationId: '2'
  },
  addCompany: {
    mutationId: '3'
  }
}
const findByMutationId = R.???
findByMutationId('2', obj) // returns addUser

回答1:


find combined with propEq and keys should work

const obj = {
  addCompany: {
    mutationId: '1'
  },
  addUser: {
    mutationId: '2'
  },
  addCompany2: {
    mutationId: '3'
  }
}
const findByMutationId = id => obj => R.find(
  R.o(R.propEq('mutationId', id), R.flip(R.prop)(obj)),
  R.keys(obj)
)

console.log(findByMutationId('2')(obj))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>

Pointfree versions for the lulz

const obj = {
  addUser: {
    mutationId: '2'
  },
  addCompany: {
    mutationId: '3'
  }
}

const findByMutationId = R.compose(
  R.o(R.head),
  R.o(R.__, R.toPairs),
  R.find,
  R.o(R.__, R.nth(1)),
  R.propEq('mutationId')
)

console.log(findByMutationId('2')(obj))

const findByMutationId2 = R.compose(
  R.ap(R.__, R.keys),
  R.o(R.find),
  R.o(R.__, R.flip(R.prop)),
  R.o,
  R.propEq('mutationId')
)

console.log(findByMutationId2('3')(obj))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.24.1/ramda.min.js"></script>



回答2:


Not sure about ramda, but if a one-liner in plain js is good for you, the following will work

const obj = {
    addCompany: {
        mutationId: '1'
    },
    addUser: {
        mutationId: '2'
    }
};

let found = Object.keys(obj).find(e => obj[e].mutationId === '2');
console.log(found);



回答3:


If you are gona use this then you might have to polyfill entries, this is good if you need both the key and the value

const obj = {
  addCompany: {
    mutationId: '1'
  },
  addUser: {
    mutationId: '2'
  },
  addCompany: {
    mutationId: '3'
  }
}

let [key, val] = Object.entries(obj).find(obj => obj[1].mutationId == '2')

console.log(key)
console.log(val)


来源:https://stackoverflow.com/questions/45820811/ramda-find-object-key-by-nested-key-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!