gpt4 book ai didi

JavaScript:如何过滤数组中的数据

转载 作者:行者123 更新时间:2023-12-03 07:25:50 27 4
gpt4 key购买 nike

我在 JS 中有以下对象:

[
{
"financial_year":1,
"mainline_revenue":18743.0,
"regional_revenue":2914.0,
"other_revenue":3198.0,
"non_operating_items":-1983.0
},
{
"financial_year":2,
"mainline_revenue":20218.0,
"regional_revenue":3131.0,
"other_revenue":3394.0,
"non_operating_items":-3233.0
},
{
"financial_year":3,
"mainline_revenue":30802.0,
"regional_revenue":6322.0,
"other_revenue":5526.0,
"non_operating_items":-1367.0
}
]

financial_year 是我想用来过滤数据的唯一标识符。如何过滤数据,例如 financial_year 为 2 并将其他值放入数组中?

最佳答案

您可以使用 filter数组上的方法。 filter 接受一个返回 true 或 false(更准确地说,是真值或假值)的回调。如果它返回 true,则该对象包含在结果数组中。

let input = [
{
"financial_year":1,
"mainline_revenue":18743.0,
"regional_revenue":2914.0,
"other_revenue":3198.0,
"non_operating_items":-1983.0
},
{
"financial_year":2,
"mainline_revenue":20218.0,
"regional_revenue":3131.0,
"other_revenue":3394.0,
"non_operating_items":-3233.0
},
{
"financial_year":3,
"mainline_revenue":30802.0,
"regional_revenue":6322.0,
"other_revenue":5526.0,
"non_operating_items":-1367.0
}
];
let output = input.filter((obj) => obj.financial_year !== 2);
console.log(JSON.stringify(output, null, 2));

或者用ES5重写:

var input = [
{
"financial_year":1,
"mainline_revenue":18743.0,
"regional_revenue":2914.0,
"other_revenue":3198.0,
"non_operating_items":-1983.0
},
{
"financial_year":2,
"mainline_revenue":20218.0,
"regional_revenue":3131.0,
"other_revenue":3394.0,
"non_operating_items":-3233.0
},
{
"financial_year":3,
"mainline_revenue":30802.0,
"regional_revenue":6322.0,
"other_revenue":5526.0,
"non_operating_items":-1367.0
}
];
var output = input.filter(function(obj) {
return obj.financial_year !== 2;
});
console.log(JSON.stringify(output, null, 2));

关于JavaScript:如何过滤数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45760426/

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