将对象及其值从对象推入AngularJS中的2D数组

时间:2017-06-21 06:37:58

标签: angularjs

这是我需要转换为数组的对象:

{
    "09:00AM - 09:30AM": "booked",
    "09:30AM - 10:00AM": "notbooked",
    "10:00AM - 10:30AM": "booked",
    "10:30AM - 11:00AM": "notbooked",
}

这是所需的输出:

[["09:00AM - 09:30AM","booked"],
 ["09:30AM - 10:00AM","notbooked"],
 ["10:00AM - 10:30AM","booked"],
 ["10:30AM - 11:00AM","notbooked"]]

我知道我可以将它用于具有键或值的一维数组:

angular.forEach($scope.slotss , function(value, key) {
    this.push(key);
},$scope.times);

3 个答案:

答案 0 :(得分:2)

只需使用[]

包装您的密钥和值即可
angular.forEach($scope.slotss , function(value, key) {
            this.push([key,value]);
        },$scope.times); 

答案 1 :(得分:1)

我会选择这样的东西:

var newSlots = [];

angular.forEach($scope.slotss, 
                function(value, key) {
                    newSlots.push([key, value]);
                });

答案 2 :(得分:1)

只使用javascript,我们可以这样做。

使用for..in循环对象。然后创建一个临时数组以从对象中推送键和值。然后将此数组推送到最终数组

var curObject = {
  "09:00AM - 09:30AM": "booked",
  "09:30AM - 10:00AM": "notbooked",
  "10:00AM - 10:30AM": "booked",
  "10:30AM - 11:00AM": "notbooked",
};
var newArray = [];

for (var keys in curObject) {
  var tempArray = [];
  tempArray.push(keys, curObject[keys]);
  newArray.push(tempArray)
}
console.log(newArray)