简体   繁体   English

如何从 state 的数据中获取 object 数组并计入 reactjs

[英]How can i get array of object from this data for state and count in reactjs

I am having data file in this array of objects form [{name,state},{name,state},{name,state},{name,state},{name,state}] I need the state data and number of people belonging to same state, for that i need an array of objects having state and it's count like [{state,count},{state, count},{state,count}] How can i get this reactjs?我在这个对象数组中有数据文件,形式为[{name,state},{name,state},{name,state},{name,state},{name,state}]我需要 state 数据和数量属于同一 state 的人,为此我需要一个具有 state 的对象数组,它的计数类似于[{state,count},{state, count},{state,count}]我怎样才能得到这个 Z3C797270102480CB7DA3E10?

This doesnt have anything to do with ReactJS, which is a library for rendering and managing UI.这与 ReactJS 没有任何关系,它是一个用于渲染和管理 UI 的库。 In JS you can use a.reduce function to do that.在 JS 中,您可以使用 a.reduce function 来执行此操作。 I will produce and array with [{name: string, count: number}]:我将使用 [{name: string, count: number}] 生成和排列:

const userArray = [{name: Riya, state: US}, {name: Chris, state: DE}]

const stateArray = userArray.reduce((newArray, currentElement) => {
  const stateExistsIndex = newArray.findIndex((state) => state.name === currentElement.state)
  if (stateExistsIndex !== -1) {
    const selectedState = newArray[stateExists] 
    newArray[stateExists] = { name: selectedState.name, count: selectedState.count++ }   
  } else {
    newArray.push({ name: currentElement.name, count: 1 })
  }

  return newArray
}, [])

This creates a new array.这将创建一个新数组。 It loops through the old array and pushes an element to the new array if an state doesnt already exists.如果 state 不存在,它将遍历旧数组并将元素推送到新数组。 If it exists it increases its count by 1. You can of course also do it in a for-of loop which might be more easily understandable.如果它存在,它将其计数增加 1。当然,您也可以在 for-of 循环中执行此操作,这可能更容易理解。

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

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