迭代我的对象对象的问题

时间:2016-04-03 19:06:53

标签: javascript object foreach

我有一个如下对象:

{ monday: { close: '10:30 PM', open: '07:30 AM' },
  tuesday: { close: '07:00 PM', open: '11:00 AM' },
  wednesday: { close: '05:30 AM', open: '11:00 AM' },
  thursday: { close: '11:00 PM', open: '06:00 AM' },
  friday: { close: '01:00 AM', open: '01:30 AM' },
  saturday: { close: '07:30 PM', open: '11:00 AM' },
  sunday: { close: 'Closed', open: 'Closed' } }

我正在尝试迭代这个并填充一个数组。

//获取营业时间

 Space.getSpaceById(req.body.spaceId, function (error, space) {

    if (error)
        throw error;

    var hours = space.hoursOfOperation;

Object.keys(hours).forEach(function(key) {
            console.log(hours[key]);
            hoursArray.push({open: hours[key].open, closed: hours[key].close})
        });
}

我的getSpaceById方法..

 module.exports.getSpaceById = function (id, callback) {
        Space.findOne({_id: id}, callback);
    };

调用.open和.close

时出现错误

我的小时对象在mongoDB中声明为

hoursOfOperation: {
        monday: {open: String, close: String},
        tuesday: {open: String, close: String},
        wednesday: {open: String, close: String},
        thursday: {open: String, close: String},
        friday: {open: String, close: String},
        saturday: {open: String, close: String},
        sunday: {open: String, close: String}
    }

2 个答案:

答案 0 :(得分:0)

我将代码粘贴到JSBin中,并进行了一些更改,这样可以正常工作,而不会更改很多代码:

Imports MySql.Data.MySqlClient

Public Sub recording()

    Dim s(2) As String
    Dim bk As New MySqlConnection("SERVER=11.111.11.11;Database=abc;uid=def;pwd=ghi")
    Dim km As New MySqlCommand


    s(1) = Date.Today
    s(2) = TimeOfDay

    Dim ip As New WebClient

        bk.Open()
        km.Connection = bk
        km.CommandText = "insert into xxx(Date,Time)values ('" _
            & s(1) & "','" _
            & s(2) & "')"
        km.ExecuteNonQuery()
        bk.Close()

End Sub

JSBIN

答案 1 :(得分:0)

只需使用for-in构造。

for (var key in foo) {
    if (foo.hasOwnProperty(key)) {
        var hours = foo[key];
        console.log(hours.close + " " + hours.open);
    }
}

Working JSFiddle