gpt4 book ai didi

javascript - 过滤 JSON 文件并查找值

转载 作者:行者123 更新时间:2023-11-28 14:20:19 25 4
gpt4 key购买 nike

我收到一个 JSON 文件,其中包含有关多个城市的天气数据。这是数据示例。

const weatherArray = [{
"Date": '5-1-19',
"Location": 'New York',
"Rainfall": 4},
{
"Date": '5-1-19',
"Location": 'Miami',
"Rainfall": 8},
{
"Date": '5-1-20',
"Location": 'New York',
"Rainfall": 9},
{
"Date": '5-1-20',
"Location": 'Miami',
"Rainfall": 2},
{
"Date": '5-1-21',
"Location": 'New York',
"Rainfall": 10},
{
"Date": '5-1-21',
"Location": 'Chicago',
"Rainfall": 9},
]

我需要做的是过滤这些数据并将每个城市的最大降雨量存储在一个数组中。我相信我的函数已经接近,但 filterData 返回 6 个未知对象的数组。

filterData = (inputArray) => {
let rain = inputArray.map(obj => rain.find(o => o.Location === obj.Location && obj.Rainfall > o.Rainfall) || rain.find(o => o.Location !== obj.Location));
return rain;
}

我希望输出数组包含与 JSON 文件中每个城市的最大降雨量关联的整个对象。

rain = [{
"Date": '5-1-19',
"Location": 'Miami',
"Rainfall": 8},
{
"Date": '5-1-21',
"Location": 'New York',
"Rainfall": 10},
{
"Date": '5-1-21',
"Location": 'Chicago',
"Rainfall": 9},
]

最佳答案

您可以拿一张 map ,收集某个位置的最大降雨量,并获取包含结果的新对象数组。

const
weatherArray = [{ Date: "5-1-19", Location: "New York", Rainfall: 4 }, { Date: "5-1-19", Location: "Miami", Rainfall: 8 }, { Date: "5-1-20", Location: "New York", Rainfall: 9 }, { Date: "5-1-20", Location: "Miami", Rainfall: 2 }, { Date: "5-1-21", Location: "New York", Rainfall: 10 }, { Date: "5-1-21", Location: "Chicago", Rainfall: 9 }],
filterData = (inputArray) => {
return Array.from(
inputArray.reduce((m, { Location, Rainfall }) =>
m.set(Location, Math.max(m.get(Location) || 0, Rainfall)), new Map),
([Location, Rainfall]) => ({ Location, Rainfall })
);
};

console.log(filterData(weatherArray));
.as-console-wrapper { max-height: 100% !important; top: 0; }

带日期。

const
weatherArray = [{ Date: "5-1-19", Location: "New York", Rainfall: 4 }, { Date: "5-1-19", Location: "Miami", Rainfall: 8 }, { Date: "5-1-20", Location: "New York", Rainfall: 9 }, { Date: "5-1-20", Location: "Miami", Rainfall: 2 }, { Date: "5-1-21", Location: "New York", Rainfall: 10 }, { Date: "5-1-21", Location: "Chicago", Rainfall: 9 }],
filterData = (inputArray) => {
return Array.from(inputArray
.reduce((m, o) => {
var temp = m.get(o.Location)
return temp && temp.Rainfall > o.Rainfall
? m
: m.set(o.Location, o);
}, new Map)
.values()
);
};

console.log(filterData(weatherArray));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 过滤 JSON 文件并查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55436154/

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