繁体   English   中英

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

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

我在这个对象数组中有数据文件,形式为[{name,state},{name,state},{name,state},{name,state},{name,state}]我需要 state 数据和数量属于同一 state 的人,为此我需要一个具有 state 的对象数组,它的计数类似于[{state,count},{state, count},{state,count}]我怎样才能得到这个 Z3C797270102480CB7DA3E10?

这与 ReactJS 没有任何关系,它是一个用于渲染和管理 UI 的库。 在 JS 中,您可以使用 a.reduce function 来执行此操作。 我将使用 [{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
}, [])

这将创建一个新数组。 如果 state 不存在,它将遍历旧数组并将元素推送到新数组。 如果它存在,它将其计数增加 1。当然,您也可以在 for-of 循环中执行此操作,这可能更容易理解。

暂无
暂无

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

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