javascript - 如何为 JavaScript 数组中的对象添加值?
问题描述
我有一个包含多个对象的数组,
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
此外,我想为每个对象添加 2 个不同的值,例如标题和正文,如下所示:-
注意:-我在数组“令牌”中有超过 300-400 个对象,所以请尝试用有效的代码回复
const tokens =
[ { to: "abc", sound: "default", title: "test", body: "test2" }
, { to: "def", sound: "Ring", title: "test", body: "test2" }
, { to: "ghi", sound: "vibrate", title: "test", body: "test2" }
]
请让我知道如何在 JavaScript 中做到这一点?
解决方案
您可以采用非变异方法并在不更改给定数据的情况下获取包含新对象的新数组。
var tokens = [{ to: "abc", sound: "default" }, { to: "def", sound: "Ring" }, { to: "ghi", sound: "vibrate" }],
result = tokens.map(o => ({ ...o, title: "test", body: "test2" }));
console.log(result);
推荐阅读
- batch-file - 需要通过使用批处理文件更改 PID 来获取进程名称
- onclick - 在 jquery 中创建新按钮时如何向 location.href 添加变量?
- codeblocks - 如何设置代码块以使用 mingw64
- mockito - 如何使用 MockWebServer Android 测试用例模拟两个 API
- java - 使用旧设备膨胀主要活动的问题
- visual-studio-code - VSCode 中所有可用命令的列表
- css - 嵌套 CSS 网格布局问题
- matlab - 同时在矩阵中设置两个值
- reactjs - 使用 React Hooks 在不同页面中获取请求
- multithreading - Vertx 线程共享内存