2

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 :-

Note:- I have more than 300-400 objects in array "tokens" so please try to reply with an efficient code

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 ?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40

2 Answers2

3

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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; }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40