我想检查是否可以在对象列表中找到字符串。
this.props.value
有一个字符串“apple, peach”,this.state.list
是一个对象列表,其中每个对象都有一个键值一对。我想看看在 this.state.list.name
中是否找到“apple, peach”。
来自 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>
)
}
最佳答案
目前还不清楚你想要什么。如果您想要列表中显示的对象列表(键值对),您可能应该执行以下操作:
newFruits = _.filter(this.state.list, o => _.contains(this.props.value, o.name))
否则,如果您只想要水果列表,可以执行以下操作:
newFruits = _.intersect(this.props.value, _.pluck(this.state.list, 'name'))
关于javascript - underscore.js _.where 用于字符串和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39173340/