簡體   English   中英

在 Javascript ES6 中如何使用鍵值對將數組中的每個元素更改為 object

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

所以我有一個數組

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

我想將其轉換為每個元素都已轉換為 object 並添加了鍵值對 play: false 的位置。

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

我也想用類似 forEach 的 JavaScript ES6 來做到這一點。 有沒有人有任何想法? 謝謝

您可以使用Array#map遍歷數組。 在每次迭代中,返回一個帶有當前audio元素的 object 和 play played:false

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

您需要使用map 方法

map 方法將遍歷數組並為數組中的每個元素創建一個新項。 在傳遞給它的回調中,您可以執行從字符串到 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}];

由於您明確提到了 forEach用法。

這里是 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