Javascript 在数组中反应计数对象属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44672209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:41:16  来源:igfitidea点击:

react count object properties in an array

javascriptarraysreactjsjavascript-objects

提问by escalepion

I am fetching data by an API. It is a movie, tv show, person database. When I search a word in the search box, it returns the related movie, tv show and person names in objects nested in an array. for example when I search "fight":

我正在通过 API 获取数据。这是一个电影,电视节目,人物数据库。当我在搜索框中搜索一个词时,它会返回嵌套在数组中的对象中的相关电影、电视节目和人物名称。例如,当我搜索“战斗”时:

    [
    0:{original_name: "? ????", id: 70813, media_type: "tv", name: "Fight My Way", vote_count: 5,…}

    1:{vote_average: 8.2, vote_count: 8057, id: 550, video: false, media_type: "movie", title: "Fight Club",…}

    2:{vote_average: 6.1, vote_count: 215, id: 345922, video: false, media_type: "movie",…}

    3:{original_name: "Fight", id: 46554, media_type: "tv", name: "Fight", vote_count: 0, vote_average: 0,…}

    4:{original_name: "The Good Fight", id: 69158, media_type: "tv", name: "The Good Fight", vote_count: 22,…}

    5:{vote_average: 0, vote_count: 0, id: 158301, video: false, media_type: "movie", title: "Fight",…}
   ]

there are more results but I cut them. As you can see there are media_typeproperties in each object. there are 3 media types as you can understand (movie, tv, person). I want to count each type.

还有更多结果,但我删掉了它们。如您所见media_type,每个对象都有属性。您可以理解有 3 种媒体类型(电影、电视、人物)。我想计算每种类型。

actually; I want the same thing in the link I guess: React: Syntax for calling setState in Switch Return

实际上; 我想在链接中也有同样的东西:React: Syntax for call setState in Switch Return

but it doesn't work for me. I tried to change simply the state of movieCount to 3 like this:

但这对我不起作用。我试图将 movieCount 的状态简单地更改为 3,如下所示:

countType() {
        this.props.movies.map(movie => {
            return() => {
            if(movie.media_type === 'movie') {
                this.setState({ movieCount: 3});
                console.log(this.state);
            }
            }
        });
    }

but it doesn't work too.and I researched on the internet this stuff in javascript documentation and forums. not about just react. but I couldn't do anything. I know it's simple.

但它也不起作用。我在互联网上研究了 JavaScript 文档和论坛中的这些东西。不仅仅是反应。但我什么也做不了。我知道这很简单。

so how can I count objects in an array according to their property types?

那么如何根据属性类型计算数组中的对象呢?

采纳答案by escalepion

ok i found the solition. thank you to poohitan for answer. i solved it through his answer.

好的,我找到了解决方案。感谢 poohitan 的回答。我通过他的回答解决了它。

countType(type) {
        const countTypes = this.props.movies.filter(movie => movie.media_type === type);
        return countTypes.length;
    }

and while i am rendering my tv results, i just call the method above with type. for example:

当我渲染我的电视结果时,我只是用类型调用上面的方法。例如:

return ( 
    <div> 
      movie count: {this.countType('movie')} 
      tv show count: {this.countType('tv')} 
    </div> 
    );

回答by poohitan

Assuming that the data you fetched from API is stored in datavariable, you can try the following code to find the count of moviemedia type in your data array:

假设您从 API 获取的数据存储在data变量中,您可以尝试以下代码来查找movie数据数组中媒体类型的计数:

const movies = data.filter(item => item.media_type === 'movie')),
  moviesCount = movies.length;

You can also dynamically calculate count of every media_typein your data array:

您还可以动态计算media_type数据数组中每个的计数:

const mediaTypes = data
    .map(dataItem => dataItem.media_type) // get all media types
    .filter((mediaType, index, array) => array.indexOf(mediaType) === index), // filter out duplicates

  counts = mediaTypes
    .map(mediaType => ({
      type: mediaType,
      count: data.filter(item => item.media_type === mediaType).length
    }));

Then countswill be something like this:

然后counts将是这样的:

[
  {
    "type": "tv",
    "count": 3
  },
  {
    "type": "movie",
    "count": 3
  }
]

回答by manas

var data = [
    { original_name: "? ????", id: 70813, media_type: "tv", name: "Fight My Way", vote_count: 5 },

    { vote_average: 8.2, vote_count: 8057, id: 550, video: false, media_type: "movie", title: "Fight Club" },

    { vote_average: 6.1, vote_count: 215, id: 345922, video: false, media_type: "movie" },

    { original_name: "Fight", id: 46554, media_type: "tv", name: "Fight", vote_count: 0, vote_average: 0 },

    { original_name: "The Good Fight", id: 69158, media_type: "tv", name: "The Good Fight", vote_count: 22 },

    { vote_average: 0, vote_count: 0, id: 158301, video: false, media_type: "movie", title: "Fight" },
]

this.types = {};

data.forEach((d) => {
    if (!this.types[d["media_type"]]) {
        this.types[d["media_type"]] = 1;
    } else {
        this.types[d["media_type"]] += 1;
    }
})

console.log(this.types);
// you will get answer { tv: 3, movie: 3 }

回答by Grace-Endy

Here's one possible way:

这是一种可能的方法:

render()  {
    let countTypes = ' '
         return ({
             list.length > 0
                 ?
                  <span> {countTypes = (list.filter(moviesFilter => 
                  moviesFilter.type.id === this.props.typeId)).length} 
                  </span>
                :
                  <DisplayMessage message="0" />
        })
}