【发布时间】:2019-10-23 13:18:00
【问题描述】:
我要处理以下 json:
[
{
"id": "device1",
"name": "dev1",
"status": "online",
"pool": "pool1",
"ports": [
{
"id": "port1",
"status": "online"
},
{
"id": "port2",
"status": "offline"
},
{
"id": "port3",
"status": "online"
}
]
},
{
"id": "device2",
"name": "dev2",
"status": "online",
"pool": "pool2",
"ports": [
{
"id": "port1",
"status": "offline"
},
{
"id": "port2",
"status": "offline"
},
{
"id": "port3",
"status": "online"
}
]
}
]
我需要计算每个池的端口数,我在想这样的事情:
devices.jsx 内部:
fetchDevices(props) {
Promise.all([
getDevices() //=> This func fetchs and return the json
]).then(results => {
let devices = flatten(results)
if (props.filter) {
devices = filter(devices, this.props.filter)
}
let pools = chain(devices)
.groupBy('pool')
.map((value, key) => ({
name: key,
devices: chain(value).filter(device => ['online','offline'].includes(device.status)).value()
}))
.values()
.map(pool => Object.assign(pool,
{
ports: countBy(pool.devices, 'ports'),
portsCount: pool.devices.reduce((memo, device) => memo + device.ports, 0)
})
)
.value()
}
...
}
稍后,在代码中我尝试显示 portsCount:
<div><span className="value">{pool.portsCount}</span> {pool.portsCount === 1 ? 'port' : 'ports'}</div>
当我运行代码时,我没有得到任何价值,代码可以吗?还是我在这里遗漏了什么?
基本上我想处理:
var arr = [
{
"id":"device1",
"pool":"pool1",
"ports": [
{
"id": "port1",
"status": "online"
},
{
"id": "port2",
"status": "offline"
}
]
},
{
"id":"device2",
"pool":"pool2",
"ports": [
{
"id": "port1",
"status": "offline"
}
]
}
];
使用 groupBy 和 .map 获取每个池的 portsCount,有什么想法吗?
【问题讨论】:
-
你是否将池的值保存到组件的状态,即setState()?否则,您将无法真正呈现它的价值。
-
请添加最终结果数据结构的示例
-
@AlexanderStaroselsky 是的,我正在保存状态,我认为我的问题是我没有在“端口”字段内循环,这就是为什么我没有得到任何价值
-
所以最终结果应该是
{ pool1: 2, pool2: 1 }? -
@OriDrori 应该是
{ pool1: 2, pool2: 1}
标签: javascript json reactjs lodash