简体   繁体   English

在 Javascript ES6 中如何使用键值对将数组中的每个元素更改为 object

[英]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.我想将其转换为每个元素都已转换为 object 并添加了键值对 play: false 的位置。

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.我也想用类似 forEach 的 JavaScript ES6 来做到这一点。 Has anyone got any ideas?有没有人有任何想法? Thank you谢谢

You can iterate over the array using Array#map .您可以使用Array#map遍历数组。 In each iteration, return an object with the current audio element and played:false :在每次迭代中,返回一个带有当前audio元素的 object 和 play 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 .您需要使用map 方法

The map method will iterate over an array and create a new item for each element in the array. map 方法将遍历数组并为数组中的每个元素创建一个新项。 In the callback that you pass to it, you can do your transformation from a string to an object as follows.在传递给它的回调中,您可以执行从字符串到 object 的转换,如下所示。

 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.由于您明确提到了 forEach用法。

Here you go.这里是 go。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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