gpt4 book ai didi

javascript - 如何使用 lodash map/countBy/groupBy 处理 JSON 字段?

转载 作者:行者123 更新时间:2023-11-28 16:58:05 27 4
gpt4 key购买 nike

我有以下 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 的归约不正确。您不是添加/返回数字,请使用相应portslength属性:

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行动中。

关于javascript - 如何使用 lodash map/countBy/groupBy 处理 JSON 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58523802/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com