我要处理以下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,有什么想法吗?
最佳答案
第一个问题是portsCount
的reduce不正确。您没有添加/返回数字,请对相应的length
使用ports
的pool
属性:
let pools = _.chain(data)
.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) => {
return memo + device.ports.length;
}, 0)
})
)
.value();
然后,在react代码中,您可以像这样循环遍历:
<div>
{this.state.pools.map(pool => (
<div>
<span className="value">{pool.portsCount}</span>{" "}
{pool.portsCount === 1 ? "port" : "ports"}
</div>
))}
</div>
这是一个正在起作用的example。