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

underscore.js _.where for string and objects

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

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'))

您可以尝试这样的操作:

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

您最好的方法是创建一个搜索词数组,并根据在搜索词中查找项目名称来过滤您的列表。参见 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);
});