我需要比较两个对象数组(源/目标)的内容。
如果目标中不存在源中的项目,则应仅添加要包括的项目。
如果目标中确实存在源中的项目,则应仅添加要排除的项目。
当前使用ramda R.differenceWith()
,但是当目标为空时出现问题。
我想知道differenceWith
是否适合这里的海豚,或者我可以使用其他功能。请给我一个例子,谢谢!
注意:即使不使用ramda,也可以得到答案。
Demo
// source
const pathHash1 = {
hash: "c4ca4238a0b923820dcc509a6f75849b",
path: "./source/file1.txt"
};
const pathHash2 = {
hash: "c81e728d9d4c2f636f067f89cc14862c",
path: "./source/file2.txt"
};
const pathHash3 = {
hash: "eccbc87e4b5ce2fe28308fd9f2a7baf3",
path: "./souce/file3.txt"
};
// target
const pathHash4 = {
hash: "eccbc87e4b5ce2fe28308fd9f2a7baf3",
path: "./target/file3.txt"
};
// works
// const source = [pathHash1, pathHash2, pathHash3]
// const target = [pathHash4]
// does no work
const source = [pathHash1, pathHash2, pathHash3]
const target = []
// result pathHash1, pathHash2
const resultInclude = R.differenceWith((x,y)=> x.hash === y.hash, source, target)
const resultExclude= R.differenceWith((x,y)=> x.hash !== y.hash, source, target)
console.log('include',resultInclude.map(x=>x.hash))
console.log('exclude',resultExclude.map(x=>x.hash))
最佳答案
对于排除情况,请使用R.innerJoin
:
const getInclude = R.differenceWith(R.eqProps('hash'))
const getExclude = R.innerJoin(R.eqProps('hash'))
const pathHash1 = {hash: "c4ca4238a0b923820dcc509a6f75849b",path: "./source/file1.txt"},pathHash2 = {hash: "c81e728d9d4c2f636f067f89cc14862c",path: "./source/file2.txt"},pathHash3 = {hash: "eccbc87e4b5ce2fe28308fd9f2a7baf3",path: "./souce/file3.txt"},pathHash4 = {hash: "eccbc87e4b5ce2fe28308fd9f2a7baf3",path: "./target/file3.txt"}
const source1 = [pathHash1, pathHash2, pathHash3]
const target1 = [pathHash4]
const source2 = [pathHash1, pathHash2, pathHash3]
const target2 = []
const getHash = R.map(R.prop('hash'))
console.log('include1', getHash(getInclude(source1, target1)))
console.log('exclude1', getHash(getExclude(source1, target1)))
console.log('include2', getHash(getInclude(source2, target2)))
console.log('exclude2', getHash(getExclude(source2, target2)))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>