使用Javascript标记数组集合中的每个数组

时间:2016-06-07 23:36:28

标签: javascript arrays

如果我有一个包含对象数组的集合,是否可以为数组中的每个数组标记或添加一个键?示例:

转换这个:

var groups = [
              [{year:"1986", key2: "foo2"}, {year:"1986", key2:"blah"}],
              [{year:"1987", key2: "baz"}, {year:"1987", key2:"beek"}],
              [{year:"1988", key2: "baz"}, {year:"1988", key2:"beek"}]
             ]

对此:

var groups = [
              a:[{year:"1986", key2: "foo2"}, {year:"1986", key2:"blah"}],
              b:[{year:"1987", key2: "baz"}, {year:"1987", key2:"beek"}],
              c:[{year:"1988", key2: "baz"}, {year:"1988", key2:"beek"}]
             ]

我的猜测是这样的,只有当我将集合变成某种对象时才有可能。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您需要将它们放在一个对象中才能通过密钥访问它们。您可以使用此功能将组转换为它。

function convertGroup (groups) {
    var new_group = {};
    var count = 1;

    for (var row in groups) {
        new_group[count] = groups[row]
        count++;
    }

    return new_group
}

将输出:

var groups = {
              1:[{year:"1986", key2: "foo2"}, {year:"1986", key2:"blah"}],
              2:[{year:"1987", key2: "baz"}, {year:"1987", key2:"beek"}],
              3:[{year:"1988", key2: "baz"}, {year:"1988", key2:"beek"}]
             }
//groups[1] = [{year:"1986", key2: "foo2"}, {year:"1986", key2:"blah"}]

答案 1 :(得分:0)

JavaScript Array索引必须是整数。如果要为值提供描述性键,则必须使用对象或HashMap

以下代码将返回一个对象{a: groups[0], b: groups[1], c: groups[2]}

var groups = [
  [{year:"1986", key2: "foo2"}, {year:"1986", key2:"blah"}],
  [{year:"1987", key2: "baz"}, {year:"1987", key2:"beek"}],
  [{year:"1988", key2: "baz"}, {year:"1988", key2:"beek"}]
];

var labels = ["a", "b", "c"];

groups = groups.reduce((result, group, index) => {
  result[labels[index]] = group;
  return result;
}, {});

console.log(groups);