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

时间:2017-09-25 21:50:24

标签: javascript arrays console.log

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

  

饮料,ABV,杜松子酒,45,精神普罗赛克,11,葡萄酒伏特加,40,精神   苦艾酒,70岁,精神雪利酒,20岁,葡萄酒烈酒,8,啤酒啤酒,4,啤酒   茴香,37,精神

这是我的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和类型显示为未定义)

  

控制台日志输出:0:对象{饮料:未定义,名称:“杜松子酒”,abv:45,...}

有可能吗?

1 个答案:

答案 0 :(得分:2)

您拥有drink功能,这很好,这是一个简单的“课程”,您可以稍后使用它创建多个饮品列表。

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