猿问

将名称分配给数组的数组

$(function() {

    $.get("https://spreadsheets.google.com/feeds/list/1VC633BXpMElJjRWvIRuZIP7UrEhuw6BdscnrV2heox0/1/public/full?alt=json", function(data) {

    var entry = data.feed.entry;

    var getKeys = Object.keys(entry[0]).slice(6);

    arr = getKeys.map(title => {

      return entry.map((el) => {

        return el[title].$t;

      }).filter((el) => {

        return el.trim();

      });

    });

    console.log(getKeys);

    console.log(arr);

  });

});

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


上面的代码会将谷歌工作表中的数据返回到数组数组中。getKeys我一直坚持为每个组分配值arr以返回新的 arr 值:


var arr = [

  gsx$fruits = ["apple", "banana"], 

  gsx$animals = ["monkey", "dog", "cat", "bear"], 

  gsx$numbers = ["one", "two", "three", "four"]

]

...这样我就可以不仅通过索引位置访问特定组。感谢您的帮助!


幕布斯6054654
浏览 140回答 2
2回答

狐的传说

我做了一些大修改,但这里有另一种选择:$(async function() {&nbsp; const data = await $.get("https://spreadsheets.google.com/feeds/list/1VC633BXpMElJjRWvIRuZIP7UrEhuw6BdscnrV2heox0/1/public/full?alt=json");&nbsp;&nbsp;&nbsp; const arrays = {};&nbsp; for (const entry of data.feed.entry) {&nbsp; &nbsp; for (const key in entry) {&nbsp; &nbsp; &nbsp; if (key.slice(0, 4) != "gsx$") continue;&nbsp; &nbsp; &nbsp; if (!entry[key].$t.trim()) continue;&nbsp; &nbsp; &nbsp; const name = key.slice(4); // optional, you could also use `key`&nbsp; &nbsp; &nbsp; if (!arrays[name]) arrays[name] = [];&nbsp; &nbsp; &nbsp; arrays[name].push(entry[key].$t);&nbsp; &nbsp; }&nbsp; }&nbsp;&nbsp;&nbsp; console.log(arrays);});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>该解决方案首先创建一个arrays将保存不同数组的对象。然后,我循环遍历这两个data.feed.entry值,并且对于每个条目,我将循环遍历键。如果key不以开头"gsx$"或者修剪后关联值为空字符串,我将跳到下一次迭代。如果我们没有跳过,请删除前 4 个字符key并将这个新值分配给name(可选)。然后检查是否arrays包含该属性name,如果不包含则将其分配arrays[name]给空数组。最后将值压入数组。我试图让这个答案易于理解,如果您有任何问题,请不要害怕发表评论。

繁花不似锦

首先你需要知道的是javaScript中的数组只是对象的一种特殊形式,而索引是整数类型的属性名称,因此如果你不仅想通过索引访问数组中的元素,还想通过属性名称访问数组中的元素,你可以使用计算属性将这些值映射到不同的名称。const keys = ['fruits', 'animals', 'numbers']const data = [&nbsp; ["apple", "banana"],&nbsp; ["monkey", "dog", "cat", "bear"],&nbsp; ["one", "two", "three", "four"]];data.forEach((item, index, array) => array[keys[index]] = item);console.log(data);console.log(data[0]);console.log(data['fruits']);虽然它可以解决您的问题,但它会改变原始数组。如果您需要访问具有属性名称的元素,我建议您使用另一种数组方法reduce,这样您可以获得新形式的数据,并且保持原始数组不变。const keys = ['fruits', 'animals', 'numbers']const data = [&nbsp; ["apple", "banana"],&nbsp; ["monkey", "dog", "cat", "bear"],&nbsp; ["one", "two", "three", "four"]];const newFormData = data.reduce((acc, cur, index) => {&nbsp; return { ...acc,&nbsp; &nbsp; [keys[index]]: cur&nbsp; }}, {});console.log(data);console.log(newFormData);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答