我有这样的数据
[
[ '@test','1.2.6-unstable' ],
[ '@test','1.3.2-unstable' ],
[ '@test','1.4.6-unstable' ],
[ '@test2','4.0.1-unstable' ],
[ '@test2','4.0.2-unstable' ],
[ '@test2','4.0.3-unstable' ],
[ '@test3','2.2.0-unstable' ],
[ '@test3','2.2.3-unstable' ],
[ '@test3','2.2.9-unstable' ],
...
]
并且我尝试按名称对它们进行分组
@test
,然后循环这些值并对每个值应用一个操作,忽略第一个值。
我的输出应该是
[
[ '@test','1.3.2-unstable' ],
[ '@test','1.4.6-unstable' ]
]
[
[ '@test2','4.0.2-unstable' ],
[ '@test2','4.0.3-unstable' ]
]
[
[ '@test3','2.2.3-unstable' ],
[ '@test3','2.2.9-unstable' ]
]
我已经查看了这些问题,但我无法应用正确的组合来获得我需要的东西
根据属性将对象数组分解为单独的数组
无法在 JS 中循环分组数组
JS用map循环遍历数组和组
我也尝试过
.shift()
和 .slice(1)
但这只会从整个原始数组中取出第一个
我的代码如下所示:
const response = await axios.get(reportURL, { headers });
const mystuff = response.data.value.reduce((acc, next) => {
acc.push(...next.versions.map((v) => [next.name, v.version]));
return acc;
}, []);
const filteredArray = mystuff.filter(([_, version]) => version.includes('-unstable'));
const map = filteredArray.reduce((acc, { name, version }) => {
if (acc.has(name)) {
acc.get(name).versions.push(version);
} else {
acc.set(name, { name, versions: [version] });
}
return acc;
}, new Map());
const result = [...map.values()];
// Loop round the array and fire off the axios
result.forEach(([name, version]) => {
const URL = `https:URL/${name}/versions/${version}?api-version=7.1-preview.1`;
我在下面添加示例代码
const data = [
["@test", "1.2.6-unstable"],
["@test", "1.3.2-unstable"],
["@test", "1.4.6-unstable"],
["@test2", "4.0.1-unstable"],
["@test2", "4.0.2-unstable"],
["@test2", "4.0.3-unstable"],
["@test3", "2.2.0-unstable"],
["@test3", "2.2.3-unstable"],
["@test3", "2.2.9-unstable"],
// ... more data
];
const groupedData = new Map();
data.forEach(([name, version], index) =>
groupedData.has(name)
? groupedData.get(name).push([name, version])
: groupedData.set(name, [])
);
groupedData.forEach((group) => console.log(group));
Object.groupBy
按嵌套数组的第一项进行分组,并仅获取值。
const
data = [['@test','1.2.6-unstable'], [ '@test','1.3.2-unstable'], ['@test','1.4.6-unstable'], ['@test2','4.0.1-unstable' ], ['@test2','4.0.2-unstable'], ['@test2','4.0.3-unstable'], ['@test3','2.2.0-unstable'], ['@test3','2.2.3-unstable'], ['@test3','2.2.9-unstable']],
grouped = Object.values(Object.groupBy(data, ([first]) => first));
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }