2016-08-26 3 views
0

객체 목록에서 문자열을 찾을 수 있는지 확인하고 싶습니다.underscore.js _ 문자열과 객체의 경우

this.props.value의 문자열은 "apple, peach"이고 this.state.list은 개체 목록이며 각 개체는 키 - 값 쌍을 가지고 있습니다. this.state.list.name에 "사과, 복숭아"가 있는지보고 싶습니다.

Underscore.js의 문서에서 : _.where(list, properties)과 나는 list으로 문자열을 입력 할 수 있다고 생각하지 않습니다. 객체 목록에 문자열이 있는지 어떻게 확인할 수 있습니까?

render() { 
    fruits = this.props.value # "apple, peach" 
    newFruits = _.where(this.props.value, this.state.list) # I want to see if "apple, peach" is found in the list of fruits in state, and if so, re-assign those values into newFruits 

    return (
     <div> 
      <p>{newFruits}</p> 
     </div> 
    ) 
} 
+0

표시 할 수있는 코드는 무엇입니까? –

+0

@MikeBrant 편집되었습니다. – patrickhuang94

답변

1

원하는 것이 분명하지 않습니다. 그냥 과일의 목록을 원한다면, 당신은 다음을 수행 할 수 있습니다, 그렇지 않으면

newFruits = _.filter(this.state.list, o => _.contains(this.props.value, o.name)) 

: 당신이 목록에 표시 객체의리스트 (키 값 쌍을)하려는 ​​경우, 당신은 아마 다음을 수행해야합니다 :

newFruits = _.intersect(this.props.value, _.pluck(this.state.list, 'name')) 
+0

죄송합니다. 명확하게 지정하지 않았습니다. 문자열 목록이 필요했고 두 번째 방법은 간단하고 우아했습니다. 감사! – patrickhuang94

0

이 같은 뭔가를 시도 할 수 있습니다 :

var newFruits=_.find(this.state.list, function (fruits) {return fruits === this.props.value })?fruits:"";

0

당신의 가장 좋은 방법은 검색어의 배열을 만들고 목록 기반을 필터링하는 것입니다 검색 용어 내에서 항목 이름 찾기. https://jsfiddle.net/92xore2x/

var fruits = 'apple, peach'; 
var list = [ 
    {name: 'apple', id: 0}, 
    {name: 'orange', id: 1}, 
    {name: 'peach', id: 2}, 
    {name: 'plum', id: 3} 
]; 

var fruitsArray = fruits.split(',').map(function(f) { return f.trim(); }); 

var results = _.filter(list, function(item) { 
    return _.contains(fruitsArray, item.name); 
});