如何从数组中获取分类对象的值

时间:2019-05-09 17:16:33

标签: javascript arrays class object foreach

我需要对一个简单的foreach函数进行硬编码,该函数会从数组中为特定属性注销具有相同值的对象列表。但是console.log一直显示未定义。我不知道我在这里做错了什么。定义了导致问题的类?如果我只需要使用类,该如何解决这个问题?

class Hive {
     constructor(apiary_name, hive_name, hive_number) {
     this.apiary_name = apiary_name;
     this.hive_name = hive_name;
     this.hive_number = hive_number;
}}

const Hive1_A1 = new Hive(A1, 'My First Hive in A1', 1111)
const Hive2_A1 = new Hive(A1, 'My Second Hive in A1', 2222)
const Hive3_A1 = new Hive(A1, 'My Third Hive in A1', 3333)
const Hive1_A2 = new Hive(A2, 'My First Hive in A2', 1111)
const Hive2_A2 = new Hive(A2, 'My Second Hive in A2', 2222)
const Hive3_A2 = new Hive(A2, 'My Third Hive in A2', 3333)

const Hives = [
    {Hive1_A1},{Hive2_A1},{Hive3_A1},{Hive1_A2},{Hive2_A2},{Hive3_A2},
]

function listHives(ApiaryName_Hive_1){
    var hives = Hives;
    hives.forEach((hive) => {
        if(hive.apiary_name === ApiaryName_Hive_1) {
            console.log(hive);
        } else {
            console.log('No hives in apiary A1 can be found')
        }
    });
}

listHives('A1')

通过调用函数listHives('A1'),我希望在console.log中仅列出Hive_1_A1,Hive_2_A1,Hive_3_A1。

1 个答案:

答案 0 :(得分:1)

执行此操作时:

const Hives = [
    {Hive1_A1},{Hive2_A1},{Hive3_A1},{Hive1_A2},{Hive2_A2},{Hive3_A2},
]

您正在使用JS速记来创建对象。这会为您提供对象列表,例如:

[{Hive1_A1: Hive1_A1}, {Hive2_A1: Hive2_A1} ...]

如果您只想要可以迭代的荨麻疹列表,请不要在列表定义中使用{},只需创建一个简单数组即可:

const Hives = [Hive1_A1, Hive2_A1, Hive3_A1...]

class Hive {
    constructor(apiary_name, hive_name, hive_number) {
    this.apiary_name = apiary_name;
    this.hive_name = hive_name;
    this.hive_number = hive_number;
}}

const Hive1_A1 = new Hive("A1", 'My First Hive in A1', 1111)
const Hive2_A1 = new Hive("A1", 'My Second Hive in A1', 2222)
const Hive3_A1 = new Hive("A1", 'My Third Hive in A1', 3333)
const Hive1_A2 = new Hive("A2", 'My First Hive in A2', 1111)
const Hive2_A2 = new Hive("A2", 'My Second Hive in A2', 2222)
const Hive3_A2 = new Hive("A2", 'My Third Hive in A2', 3333)

const Hives = [Hive1_A1, Hive2_A1, Hive3_A1, Hive1_A2, Hive2_A2, Hive3_A2]

function listHives(ApiaryName_Hive_1){
   var hives = Hives;
   hives.forEach((hive) => {
       if(hive.apiary_name === ApiaryName_Hive_1) {
           console.log(hive);
       } else {
           console.log('No hives in apiary A1 can be found')
       }
   });
}

listHives('A1')