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 ?

4
  • 2
    yes, you can do it with javascript. Commented Feb 22, 2020 at 21:18
  • Please Let me know I am totally stuck into this. Commented Feb 22, 2020 at 21:19
  • do you want a new array with new objects? Commented Feb 22, 2020 at 21:22
  • both will work for me, if possible let me know for both the ways.(there are 300-400 objects in array so try with an efficient way) Commented Feb 22, 2020 at 21:24

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Isn't creating new objects slower than writing to the same object?
@TheMaster, yes it is. does it matter?
I mean op said, so please try to reply with an efficient code. So, I was wondering if it is efficient. You specifically mentioned non mutate approach. So, just wondering if I'm missing something.
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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.