为 array.push() 中的对象命名

在我的代码的一部分中,我从 JSON 文件中提取数据并将其放置在基于对象的数组中。


我成功接收数据,并且可以将每个数据放在数组中的单个对象上。唯一的问题是,我想为每个对象命名。


var playlist_data = {

  "Music1": {

    "soundcloud": "Soundcloud Music 1",

    "spotify": "Spotify Music 1"

  },

  "Music2": {

    "soundcloud": "Soundcloud Music 2",

    "spotify": "Spotify Music 2"

  },

  "Music3": {

    "soundcloud": "Soundcloud Music 3",

    "spotify": "Spotify Music 3"

  },

  "Music4": {

    "soundcloud": "Soundcloud Music 4",

    "spotify": "Spotify Music 4"

  }

};

var links = [];

$.each(playlist_data, function(index, element) {

  links.push({

    spotify: element.spotify,

    soundcloud: element.soundcloud,

  });

});


console.log(links);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

在上面的代码中似乎复制了相同的 JSON 数据,但它是一个简化版本。

所以结果我想这样称呼它links.Music2links.Music2.spotify


Qyouu
浏览 243回答 3
3回答

繁华开满天机

由于您似乎想将spotify用作links.JS中有两种类型的数组:标准数组是: [ ]关联数组是:{ }!如您所见,您可以将{ }which 也用作 javascript 中的对象作为数组。然后你就可以用它spotify作为钥匙了。所以你的代码将如下所示:var links = {};$.each(playlist_data, function(index, element) {&nbsp; links[index] = {&nbsp; &nbsp; spotify: element.spotify,&nbsp; &nbsp; soundcloud: element.soundcloud,&nbsp; };});console.log(links_s.Music1.spotify) // Spotify Music 1

蛊毒传说

你可以用下面的代码命名你的每个 objvar playlist_data = {&nbsp; "Music1": {&nbsp; &nbsp; "soundcloud": "Soundcloud Music 1",&nbsp; &nbsp; "spotify": "Spotify Music 1"&nbsp; },&nbsp; "Music2": {&nbsp; &nbsp; "soundcloud": "Soundcloud Music 2",&nbsp; &nbsp; "spotify": "Spotify Music 2"&nbsp; },&nbsp; "Music3": {&nbsp; &nbsp; "soundcloud": "Soundcloud Music 3",&nbsp; &nbsp; "spotify": "Spotify Music 3"&nbsp; },&nbsp; "Music4": {&nbsp; &nbsp; "soundcloud": "Soundcloud Music 4",&nbsp; &nbsp; "spotify": "Spotify Music 4"&nbsp; }};var links = [];$.each(playlist_data, function(index, element) {&nbsp; links.push({&nbsp; &nbsp; spotify: element.spotify,&nbsp; &nbsp; soundcloud: element.soundcloud,&nbsp; });});let myMusic = {};for(let x = 0 ; x < links.length ; x++){&nbsp; &nbsp; let z = Number(x+1);&nbsp; &nbsp; myMusic["music"+z] = links[x];}console.log(myMusic.music1);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript