我在这个对象数组中拥有数据文件形式 [{name,state},{name,state},{name,state},{name,state},{name,state}]
我需要状态数据和属于同一状态的人数,为此我需要一个具有状态的对象数组,它的计数类似于 [{state,count},{state, count},{state,count}]
我怎样才能得到这个reactjs?
最佳答案
这与 ReactJS 没有任何关系,ReactJS 是一个用于渲染和管理 UI 的库。
在 JS 中,您可以使用 .reduce 函数来做到这一点。我将使用 [{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
}, [])
这将创建一个新数组。如果状态不存在,它会遍历旧数组并将元素推送到新数组。如果它存在,它将其计数增加 1。当然,您也可以在 for-of 循环中执行此操作,这可能更容易理解。
关于javascript - 我如何从这些数据中获取对象数组以获取状态并在 reactjs 中计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67148997/