[英]How to add value to an object which is inside an array in JavaScript?
I have an array with multiple object into it,我有一个包含多个对象的数组,
const tokens =
[ { to: "abc", sound: "default" }
, { to: "def", sound: "ring" }
, { to: "ghi", sound: "vibrate" }
]
Further i want to add 2 different value say title and body to each object something like this :-此外,我想为每个对象添加 2 个不同的值,例如标题和正文,如下所示:-
Note:- I have more than 300-400 objects in array "tokens" so please try to reply with an efficient code注意:- 我在数组“tokens”中有超过 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" }
]
Please Let me know how this can be done in JavaScript ?请让我知道如何在 JavaScript 中完成此操作?
You could take a non mutate approach and get a new array with new objects without altering the given data.您可以采用非变异方法并在不更改给定数据的情况下获取包含新对象的新数组。
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);
you can also use this way你也可以用这种方式
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; }
an other way:其它的办法:
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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.