json 如何从JavaScript数组中获取键和值

kkbh8khc  于 2023-11-20  发布在  Java
关注(0)|答案(1)|浏览(76)

我有一个JavaScript数组,我试图提取团队(团队A,团队B),并把他们放在一个数组,然后把责任放在一个单独的数组,同时保持秩序。
下面详细介绍了当前数组输出,JS代码显示和预期结果
阵法:

[
  {
    "Team A": 2,
    "Team B": 3
  }
]

字符串
JS:

var retValue = [];  
  var count = this.jsonArray.map((cv) => {
    var teams = cv["teams"].reduce((acc, team) => {
      acc[team["value"]] = team["text"];
      return acc;
    }, {});
    return cv["duty"].reduce((acc, duty) => {
      acc[teams[duty["parentId"]]] = acc[
        teams[duty["parentId"]]
      ]
        ? acc[teams[duty["parentId"]]] + 1
        : 1;
      return acc;
    }, {});
  });

  retValue = Object.keys(count).map((cv) => count[cv]);
  console.debug(retValue);  //working
  
  
  var getKeys = [];
  getKeys = Object.keys(retValue); //not working
   
  var getValues = [];
  ....


预期结果:

[Team A, Team B] , [2 , 3]


原始JS数组/对象:

{
  "jsonArray": [{
    "teams": [

      {
        "text": "Team A",
        "id": 1,
        "value": 500,
        "parentId": 333
      },
      {
        "text": "Team B",
        "id": 2,
        "value": 600,
        "parentId": 444
      }

    ],
    "duty": [

      {
        "text": "Meetings",
        "id": 11,
        "value": 100,
        "parentId": 500
      },
      {
        "text": "Lunch",
        "id": 12,
        "value": 101,
        "parentId": 500
      },
      {
        "text": "Time Cards",
        "id": 13,
        "value": 102,
        "parentId": 600
      },

      {
        "text": "Parking",
        "id": 14,
        "value": 103,
        "parentId": 600

      },
      {
        "text": "Breakfast",
        "id": 15,
        "value": 104,
        "parentId": 600
      }
    ]

  }]
};

vi4fp9gy

vi4fp9gy1#

我想你可以这样解决:

var retValue = [];
var count = jsonArray.map((cv) => {
  var teams = cv["teams"].reduce((acc, team) => {
    acc[team["value"]] = team["text"];
    return acc;
  }, {});
  return cv["duty"].reduce((acc, duty) => {
    var teamName = teams[duty["parentId"]];
    acc[teamName] = acc[teamName] ? acc[teamName] + 1 : 1;
    return acc;
  }, {});
});

console.debug(count);  // array of team names and their corresponding duty counts.

var getKeys = Object.keys(count[0]);

console.debug(getKeys);  // array of team names

var getValues = Object.values(count[0]); 

console.debug(getValues);  // array of counts

字符串

相关问题