简体   繁体   中英

Make a JSON array of objects out of an array of strings

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' }
]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM