1

I have an array.

messages = ['hi', 'heelo', 'apple'];

Write a function to return:

[
    { msg: messages[0], type: 'A', label: 'msg' },
    { msg: messages[2], type: 'A', label: 'msg' },
    { msg: messages[2], type: 'A', label: 'msg' }
]
8
  • 2
    Let's see what you've tried, only then can we help you. Commented Nov 9, 2017 at 18:52
  • 1
    You should make an effort first. Commented Nov 9, 2017 at 18:52
  • [0] and then double [2]? Doesn't make any sense. And these hardcoded type and label keys... Commented Nov 9, 2017 at 18:52
  • @Kinduser Simple error on his side. Commented Nov 9, 2017 at 18:55
  • Possible duplicate of Convert array of strings to array of objects Commented Nov 9, 2017 at 18:57

1 Answer 1

-1

You can use Array#map:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

var messages = ['hi', 'heelo', 'apple'];

var messages_1 = JSON.stringify(messages.map(function(el) {
  return {
    msg: el,
    type: "A",
    label: "msg"
  };
}));

console.log(messages_1);

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

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.