首页 > 解决方案 > 如何为 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 中做到这一点?

标签: javascriptarraysreact-nativeobjectarrayobject

解决方案


您可以采用非变异方法并在不更改给定数据的情况下获取包含新对象的新数组。

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);


推荐阅读