如何向 JavaScript 中的数组内的 object 添加值?
How to add value to an object which is inside an array in JavaScript?
我有一个包含多个 object 的数组,
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
此外,我想为每个 object 添加 2 个不同的值,例如标题和 body,如下所示:-
注意:- 我在数组 "tokens" 中有超过 300-400 objects 所以请尝试用有效的代码回复
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);
你也可以这样使用
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
tokens.forEach(e=>{ e.title= "test"; e.body= "test2" })
console.log( tokens )
.as-console-wrapper { max-height: 100% !important; top: 0; }
另一种方式:
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
newElements = {title:'test', body:'test2'}
;
tokens.forEach(e=>Object.assign(e, newElements))
console.log( tokens )
.as-console-wrapper { max-height: 100% !important; top: 0; }
我有一个包含多个 object 的数组,
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
此外,我想为每个 object 添加 2 个不同的值,例如标题和 body,如下所示:-
注意:- 我在数组 "tokens" 中有超过 300-400 objects 所以请尝试用有效的代码回复
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);
你也可以这样使用
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
tokens.forEach(e=>{ e.title= "test"; e.body= "test2" })
console.log( tokens )
.as-console-wrapper { max-height: 100% !important; top: 0; }
另一种方式:
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
newElements = {title:'test', body:'test2'}
;
tokens.forEach(e=>Object.assign(e, newElements))
console.log( tokens )
.as-console-wrapper { max-height: 100% !important; top: 0; }