【问题标题】:In Javascript ES6 How to change each element in an array to an object with key value pairs在Javascript ES6中如何将数组中的每个元素更改为具有键值对的对象
【发布时间】:2021-07-13 01:54:15
【问题描述】:

所以我有一个数组

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

我想将其转换为每个元素都已转换为具有键值对的对象的位置 play : false 添加。

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

我也想用 JavaScript ES6 和 forEach 之类的东西来做这件事。有没有人有任何想法?谢谢

【问题讨论】:

  • ES6 有什么特别之处?为什么不是 ES2016 到 ES2021?

标签: javascript node.js arrays ecmascript-6


【解决方案1】:

您可以使用Array#map 遍历数组。在每次迭代中,返回一个具有当前audio 元素和played:false 的对象:

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

const res = audioList.map(audio => ({ audio, played: false }));

console.log(res);

【讨论】:

  • 这就是我所做的,但没有括号。谢谢。
  • @woisme 这是迄今为止最简单的解决方案,可能是我个人在生产中使用的解决方案。您始终可以使用 song => ({ audio: song }) 之类的东西,但 audio => ({ audio }) 更加简洁,并且为您的 played 属性等新属性留下了更长的属性声明。很好的解决方案,Majed。
【解决方案2】:

您需要使用map method

map 方法将遍历一个数组并为数组中的每个元素创建一个新项。在您传递给它的回调中,您可以执行从字符串到对象的转换,如下所示。

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

【讨论】:

  • 这是最全面的,它教会了我新的思考方式。感谢您抽出宝贵时间将其表述得如此清晰和翔实。
【解决方案3】:

既然您明确提到了 forEach 的用法。

给你。

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

【讨论】:

  • 这是完美的。感谢您抽出宝贵时间回复。最后我把自己弄得一团糟,总是感觉不对劲。
猜你喜欢
  • 1970-01-01
  • 2018-10-18
  • 2019-08-18
  • 1970-01-01
  • 2018-01-06
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 2021-07-17
相关资源
最近更新 更多