gpt4 book ai didi

javascript - 带有对象的嵌套数组,lodashmeanBy

转载 作者:行者123 更新时间:2023-12-02 22:02:41 27 4
gpt4 key购买 nike

有人可以帮助我了解如何进行这项工作吗?每当我感觉自己开始理解 Javascript 中的数组和对象时,事实证明我仍然没有理解。

我正在尝试使用 lodash meanBy 获取以下数据结构中所有价格的平均值

[
{
date: "2019-12-17",
items: [
{ id: "1", state: "accepted", price: "90.5" },
{ id: "2", state: "rejected", price: "20.0" },
{ id: "3", state: "open", price: "10.5" },
]
},
{
date: "2019-12-18",
items: [
{ id: "4", state: "open", price: "450.0" },
{ id: "5", state: "rejected", price: "40.1" },
{ id: "6", state: "accepted", price: "50.9" },
]
}
]

如果您提供答案,您能否尝试解释一下如何选择嵌套在项目中的某些内容,因为这就是我在迷失之前所能得到的。

最佳答案

在这种情况下,不必选择嵌套值,而是更容易将项目展平为单个数组,然后应用 _.meanBy()。此外,价格是字符串,而不是数字,因此您需要对其进行转换。

使用Array.flatMap()items展平为单个数组,然后使用_.meanBy(),并获取价格数值:

const data = [{"date":"2019-12-17","items":[{"id":"1","state":"accepted","price":"90.5"},{"id":"2","state":"rejected","price":"20.0"},{"id":"3","state":"open","price":"10.5"}]},{"date":"2019-12-18","items":[{"id":"4","state":"open","price":"450.0"},{"id":"5","state":"rejected","price":"40.1"},{"id":"6","state":"accepted","price":"50.9"}]}]

const result = _.meanBy(_.flatMap(data, 'items'), o => +o.price)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

另一种方法是获取总体平均值,即分别获取每个items数组的平均值,然后获取所有平均值的平均值。

const data = [{"date":"2019-12-17","items":[{"id":"1","state":"accepted","price":"90.5"},{"id":"2","state":"rejected","price":"20.0"},{"id":"3","state":"open","price":"10.5"}]},{"date":"2019-12-18","items":[{"id":"4","state":"open","price":"450.0"},{"id":"5","state":"rejected","price":"40.1"},{"id":"6","state":"accepted","price":"50.9"}]}]

const result = _.meanBy(data, ({ items }) => _.meanBy(items, o => +o.price))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

关于javascript - 带有对象的嵌套数组,lodashmeanBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59825379/

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