简体   繁体   English

反应:在Object.keys上调用过滤器

[英]React: Calling filter on Object.keys

A React component is passed a state property, which is an object of objects: 一个React组件被传递了一个state属性,该属性是一个object对象:

{
    things: {
        1: {
            name: 'fridge',
            attributes: []
        },
        2: {
            name: 'ashtray',
            attributes: []
        }
    }
}

It is also passed (as a router parameter) a name . 它还传递了一个name (作为路由器参数)。 I want the component to find the matching object in the things object by comparing name values. 我希望组件通过比较name值在things对象中找到匹配的对象。

To do this I use the filter method: 为此,我使用filter方法:

Object.keys(this.props.things).filter((id) => {
    if (this.props.things[id].name === this.props.match.params.name) console.log('found!');
    return (this.props.things[id].name === this.props.match.params.name);
});

However this returns undefined . 但是,这将返回undefined I know the condition works because of my test line (the console.log line), which logs found to the console. 我所知道的情况,因为工作我的测试线(的console.log线),它记录found到控制台。 Why does the filter method return undefined ? 为什么filter方法返回undefined

Object.keys returns an array of keys (like maybe ["2"] in your case). Object.keys返回一个键数组(例如您的情况下可能是["2"] )。 If you are interested in retrieving the matching object , then you really need Object.values . 如果您对检索匹配的对象感兴趣,那么您确实需要Object.values And if you are expecting one result, and not an array of them, then use find instead of filter : 如果您期望一个结果而不是它们的数组,请使用find而不是filter

Object.values(this.props.things).find((obj) => {
    if (obj.name === this.props.match.params.name) console.log('found!');
    return (obj.name === this.props.match.params.name);
});

Be sure to return that result if you use it within a function. 如果在函数中使用该结果,请确保return该结果。 Here is a snippet based on the fiddle you provided in comments: 这是一个基于您在注释中提供的小提琴的片段:

 var state = { things: { 1: { name: 'fridge', attributes: [] }, 2: { name: 'ashtray', attributes: [] } } }; var findThing = function(name) { return Object.values(state.things).find((obj) => { if (obj.name === name) console.log('found!'); return obj.name === name; }); } var result = findThing('fridge'); console.log(result); 

You need to assign the result of filter to a object and you get the result as the [id] . 您需要将filter的结果分配给一个对象,并以[id]获得结果。 You then need to get the object as this.props.things[id] 然后,您需要获取对象为this.props.things[id]

 var data = { things: { 1: { name: 'fridge', attributes: [] }, 2: { name: 'ashtray', attributes: [] } } } var name = 'fridge'; var newD = Object.keys(data.things).filter((id) => { if (data.things[id].name === name) console.log('found!'); return (data.things[id].name === name); }); console.log(data.things[newD]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM