首页 > 解决方案 > 将对象转换为数组 Angular

问题描述

我是 javascript 和 Angular 的新手。假设我有一个带有{"xyz":{Key:info}}. 我想添加{Key:info}到一个数组中。

我想让“xyz”成为一个数组。例如:{"xyz":[{Key:info}]}这样我就可以推送更多{Key:info}入该数组- {"xyz":[{Key:info},{Key:info},{Key:info}]}.

我也需要每次检查是否xyz是否为对象,然后将其设为数组并仅推送一次。

我不知道如何使用 Angular javascript 做到这一点。

编辑:- 添加原始 JSON

$scope.ContentObj= {
      "attribute-set": [
        {
          "attribute": [
            {
              "_name": "text-align",
              "__prefix": "xsl",
              "__text": "end"
            },
            {
              "_name": "end-indent",
              "__prefix": "xsl",
              "__text": "10pt"
            }
          ],
          "_name": "odd__header",
          "__prefix": "xsl"
        },
        {
          "attribute": {
            "_name": "font-weight",
            "__prefix": "xsl",
            "__text": "bold"
          },
          "_name": "pagenum",
          "__prefix": "xsl"
        }
      ],
      "_version": "2.0",
      "__prefix": "xsl"
    }

标签: javascriptarraysangularjsjson

解决方案


这可能是你要问的。

if (!angular.isArray($scope.yourObject.xyz)){
    $scope.yourObject = {
        xyz: []
    }
}
$scope.yourObject.xyz.push({Key:'info'})

推荐阅读