javascript - 我们如何将 javascript 数组修改为数组对象?
问题描述
我有这个数组arr = [{id:1},{id:2},{id:3},{id:5},{id:5}]
我想修改数组,比如索引 0 - 1 是第一个,2 -3 是第二个,4 - 5 是第三个等等
结果数组:
[first:[{id:1},{id:2}],second:[{id:3},{id:5}],third:[{id:5}]]
如何修改这种类型的数组?
解决方案
您期望的结果不是有效的数组。
[first: [{},{}]]
它应该是这样的数组
[[{},{}],[{},{}]]
或一个物体
{"first":[{},{}],"second":[{},{}]}
下面的代码将您的输入转换为一个数组,如果您正在寻找一个对象,则可以通过一些小的修改轻松地将其修改为一个对象。
const arr = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 5 }, { id: 5 }];
let result = arr.reduce((acc, current, index) => {
if (index % 2 == 0) {
acc.push([current]);
} else {
acc[Math.floor(index / 2)].push(current);
}
return acc;
}, []);
推荐阅读
- python - 打开 CV (python) 我的代码存在 imread 问题。它没有按预期工作所有输出都为零
- eslint - 将 .eslintrc 重新定位到父级后,ESLint 找不到配置“prettier/@typescript-eslint”
- javascript - Discord.js 从 JSON 文件中获取数据返回“未定义”
- javascript - 如何在字符串 smtpjs 中添加换行符
- ios - 没有 AppDelegate 的 SwiftUI 远程推送通知 - 有可能吗?
- python - 随机引号被添加到我的列表中
- python - 如何消除此 Kivy 间距问题
- python - 有没有办法让 gettext 注释提取器查找字符串的内联注释而不是之前的行?
- c# - 从变量类型获取默认相等比较器?
- asp.net-core - 我可以使用当前 NTML 上下文从 WebAPI 控制器(或 BlazorComponent)内部发出请求吗?