简体   繁体   中英

In Javascript ES6 How to change each element in an array to an object with key value pairs

So I have an array

const audioList = ["song1", "song2", "song3", "song3"];

I want to convert it into where every element has been turned into an object with a key-value pair of played: false added.

const newaudioList = [{audio : "song1", played : false}, {audio : "song2", played : false}, {audio : "song3", played : false}]

I also want to do this with JavaScript ES6 with something like forEach. Has anyone got any ideas? Thank you

You can iterate over the array using Array#map . In each iteration, return an object with the current audio element and played:false :

 const audioList = ["song1", "song2", "song3", "song3"]; const res = audioList.map(audio => ({ audio, played: false })); console.log(res);

You'll want to use the map method .

The map method will iterate over an array and create a new item for each element in the array. In the callback that you pass to it, you can do your transformation from a string to an object as follows.

 const audioList = ["song1", "song2", "song3", "song3"]; /* This is one way to accomplish this in one line. It is pretty easy to read and understand. The outer () is a little weird, but necessary so JavaScript will see the inside of it as a new object and not a 'closure'. */ const newAudioList1 = audioList.map(item => ({ audio: item, played: false })); console.log(newAudioList1); /* This is another way to accomplish the above and might seem a little too verbose, but this approach can be helpful for debugging purposes. The stack trace will have this method name, whereas above, it will only show an anonymous function and might be harder to track down the source of the error. */ function transformToObject(s) { return { audio: s, played: false }; } const newAudioList2 = audioList.map(transformToObject); console.log(newAudioList2); // const newaudioList = [{audio: "song1", played: false}, {audio: "song2", played: false}, {audio: "song3", played: false}];

Since you explicitly mentioned forEach usage.

Here you go.

const audioList = ["song1", "song2", "song3", "song3"];
var newaudioList = [];
audioList.forEach((e) => {
    newaudioList.push({
        audio: e,
        played: false
    })
});

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