2017-03-05 5 views
0

일부 데이터가 포함 된 개체가 있습니다. 특정 키를 선택하고 두 키가 일치하면 키와 값도 생략하고 싶습니다. 내가하고 싶은 무엇Ramda는 키와 값이 일치 할 경우 생략합니다.

const obj = { 
    title: 'some title', 
    description: 'some descrption', 
    image: 'default_image.png' 
} 

, descriptionimage을 추출하고 'default_image.png'의 값이있는 경우 다음 image를 생략하는 것입니다 : 여기 내 개체입니다.

const fn = R.compose(
    // if image === 'default_image.png' then omit it 
    R.pickAll(['description', 'image']) 
) 

위의 두 번째 부분에 가장 적합한 ramda 기능이 무엇인지 확실하지 않습니다. 당신은 두 개의 서로 다른 기능과 내가 생각할 수 ramda의 ifElse

const obj1 = { 
    title: 'some title', 
    description: 'some descrption', 
    image: 'default_image.png' 
} 

const obj2 = { 
    title: 'title', 
    description: 'descrption', 
    image: 'image.png' 
} 

const withImage = R.pickAll(['description', 'image']); 
const withoutImage = R.pickAll(['description']); 
const hasDefault = obj => obj['image'] == 'default_image.png' 

const omit = R.ifElse(hasDefault, withoutImage, withImage); 

console.log(omit(obj1)); 
console.log(omit(obj2)); 

가장 간단한 방법으로 적용 분야를 점검 한 부울 함수를 만들 수 있습니다 사용

답변

2

나는 것 아마도 뭔가를 할 것입니다.

const fn = pipe(
    when(propEq('image', 'default_image.png'), dissoc('image')), 
    pick(['description', 'image']) 
); 

dissoc은 특정 키가 제거 된 객체의 복사본을 반환합니다. propEq은 객체의 주어진 속성이 제공된 값과 일치하는지 여부를 테스트합니다. when은 술어와 변환 함수를 사용합니다. 술어가 제공된 데이터와 일치하면 해당 데이터에서 변환 함수를 호출 한 결과가 리턴되고 그렇지 않으면 데이터가 변경되지 않고 리턴됩니다.

pickAll 대신 pick을 선택했습니다. 유일한 차이점은 pick은 찾지 못한 키를 건너 뜁니다. pickAll은 값이 undefined 인 값을 반환합니다.

Ramda REPL에서 확인할 수 있습니다. 당신은 항상 대신 개별 개체의 목록에서 작동하려고한다면

, 당신은 pick에서 project로 전환 할 수 있습니다

const fn = pipe(
    project(['description', 'image']), 
    map(when(propEq('image', 'default_image.png'), dissoc('image'))) 
); 

fn(objects); 

이것은 또한 Ramda REPL 볼 수 있습니다.

+0

환상적인 대답, 스캇 감사합니다! – gosseti

2

pickBy

const hasDefault = (val, key) => key == 'image' && val == 'default_image.png' ? false : true 
console.log(R.pickBy(hasDefault, obj1)) 
console.log(R.pickBy(hasDefault, obj2)) 
+1

'R.compose'를 호출 할 필요가 없습니다. –

+0

@ScottSauyet niice! 모양이 더 좋아 보인다. –