javascript - underscore.js _.where 用于字符串和对象

标签 javascript reactjs underscore.js

我想检查是否可以在对象列表中找到字符串。

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/

相关文章:

javascript - Ember.js 和 ArrayController

javascript - 如何根据另一个请求的响应向 API 发出请求?无法在回调中调用 React Hook "useSwr"

javascript - 如何使用单独的函数动态组合React组件?

javascript - 按特定要求拆分数组

javascript - 外部 Javascript 函数不更新 Backbone JS 中的 html div

javascript - 比较 2 个不可变列表是否相等

javascript - 检查对象是否具有与数组中定义的字段值相同的值

javascript - underscore.js .keys 和 .omit 没有按预期工作

reactjs - 使用子域部署 React 应用程序不起作用

reactjs - Material-UI React.js,有没有办法让 ListItem 和 ListItem 的头像都有一个 onClick 事件?