gpt4 book ai didi

javascript - 根据对象中的值将对象数组拆分为两个

转载 作者:行者123 更新时间:2023-12-01 23:33:19 25 4
gpt4 key购买 nike

我一直在尝试(并努力)找出如何根据键值对拆分对象数组

长话短说,我有一个火车停靠站的列表,需要将之前的停靠站和 future 的停靠站分开。

我正在处理的数据如下所示:

[{station_code: "SOC", station_name: "Southend Central" },
{station_code: "WCF", station_name: "Westcliff On Sea" },
{station_code: "CHW", station_name: "Chalkwell" },
{station_code: "LES", station_name: "Leigh On Sea" },
{station_code: "BEF", station_name: "Benfleet" },
{station_code: "PSE", station_name: "Pitsea" },
{station_code: "BSO", station_name: "Basildon" }]

我想有两个新的数组,它们被分割在,例如 Leigh On Sea.. 像这样:

之前的站点:

[{station_code: "SOC", station_name: "Southend Central" },
{station_code: "WCF", station_name: "Westcliff On Sea" },
{station_code: "CHW", station_name: "Chalkwell" }]

后续停止:

[{station_code: "BEF", station_name: "Benfleet" },
{station_code: "PSE", station_name: "Pitsea" },
{station_code: "BSO", station_name: "Basildon" }]

如果可能的话,它还有助于潜在地返回当前站(leigh on sea)以及其中包含对象的单独数组...

我遇到过这个,但是我想不出如何调整它以查看对象以找到电台名称:

const getAllAfter = (current) => {
var myArr = new Array("alpha", "beta", "gamma", "delta");
var i = myArr.indexOf(current);
return i > -1 ? myArr.slice(0, i) : [];
};

提前致谢! :)

最佳答案

使用Array.findIndex()找到分离item的索引,然后使用Array.slice()得到前数组,item,和之后的数组。

const splitAt = (predicate, arr) => {
const index = arr.findIndex(predicate);

return [
arr.slice(0, index),
arr[index],
arr.slice(index + 1)
];
};


const data = [{"station_code":"SOC","station_name":"Southend Central"},{"station_code":"WCF","station_name":"Westcliff On Sea"},{"station_code":"CHW","station_name":"Chalkwell"},{"station_code":"LES","station_name":"Leigh On Sea"},{"station_code":"BEF","station_name":"Benfleet"},{"station_code":"PSE","station_name":"Pitsea"},{"station_code":"BSO","station_name":"Basildon"}];

const [before, separator, after] = splitAt(o => o.station_name === 'Leigh On Sea', data);

console.log({ before, separator, after });

关于javascript - 根据对象中的值将对象数组拆分为两个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65945891/

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