如何有选择地打印数组中列表的一部分?

How to selectively print portions of a list in an array?

所以我有一个充满饮料数据的 csv

Drink,ABV,Type Gin,45,Spirit Prosecco,11,Wine Vodka,40,Spirit Absinthe,70,Spirit Sherry,20,Wine Stout,8,Beer Lager,4,Beer Ouzo,37,Spirit

这是我的 JS,我希望它遍历数组并检查精神,然后在控制台中打印出精神。

var spirit_list = [];

function drink(a,b,c) {
    this.Drink = a;
    this.ABV = b;
    this.Type = c;

}

d3.csv("alcohol.csv", function(data) {
    data.forEach(function(d){
        myDrink = new drink(); // new drink object
        if (d.Type === "Spirit"){ //logic to grab spirits
            myDrink.name = d.Drink; // assign obj values
            myDrink.abv = +d.ABV;
            spirit_list.push(myDrink) // push the obj to a list
        };
    console.log(spirit_list);
       // d.abv = +d.ABV; // + : converts into a number, instead of the default string
    })
    // console.log(data); // data becomes sucked into console.log and becomes an array
    // fyi everything is parsed into strings (from the spreadsheet .csv to the log)
});

}

但我只想显示名称和 ABV,我不希望所有其他对象 属性(饮料、abv 和类型显示为未定义)

Console Log output: 0: Object { Drink: undefined, name: "Gin", abv: 45, … }

可以吗?

你有你的 drink 功能,这很好,它很简单 'class' 你可以稍后使用它来创建一个包含多种饮料的列表。

function drink(a,b,c) {
    this.Drink = a;
    this.ABV = b;
    this.Type = c;

}

您在 drink 上定义的三个属性是您在创建每个 myDrink 对象时应该使用的。像这样更改您的创建代码...将饮料创建移动到 if 语句中并仅添加您想要的属性。如果您有不需要在这种情况下使用的属性,只需 delete 它们:

if (d.Type === "Spirit"){ //logic to grab spirits
  myDrink = new drink(d.Drink, d.ABV, d.Type); // new drink object
  delete myDrink['Type'];
  spirit_list.push(myDrink) // push the obj to a list
};

这是一个完整的例子:

var spirit_list = [];

function drink(a,b,c) {
    this.Drink = a;
    this.ABV = b;
    this.Type = c;

}

getData().forEach(function(d){
    myDrink = new drink(); // new drink object
    if (d.Type === "Spirit"){ //logic to grab spirits
      myDrink = new drink(d.Drink, d.ABV, d.Type);
      delete myDrink['Type'];
      spirit_list.push(myDrink) // push the obj to a list
    };
   // d.abv = +d.ABV; // + : converts into a number, instead of the default string
});

console.log(spirit_list);
// console.log(data); // data becomes sucked into console.log and becomes an array
// fyi everything is parsed into strings (from the spreadsheet .csv to the log)

function getData() {
  return [
 {
   "Drink": "Gin",
   "ABV": 45,
   "Type": "Spirit"
 },
 {
   "Drink": "Prosecco",
   "ABV": 11,
   "Type": "Wine"
 },
 {
   "Drink": "Vodka",
   "ABV": 40,
   "Type": "Spirit"
 },
 {
   "Drink": "Absinthe",
   "ABV": 70,
   "Type": "Spirit"
 },
 {
   "Drink": "Sherry",
   "ABV": 20,
   "Type": "Wine"
 },
 {
   "Drink": "Stout",
   "ABV": 8,
   "Type": "Beer"
 },
 {
   "Drink": "Lager",
   "ABV": 4,
   "Type": "Beer"
 },
 {
   "Drink": "Ouzo",
   "ABV": 37,
   "Type": "Spirit"
 }
];
}