根据键将json数组划分为json数组

时间:2018-02-23 10:29:50

标签: javascript arrays json

我有一个像这样的json数组:

    [
      {id:1, another_id:1},
      {id:2, another_id:1},
      {id:3, another_id:2}
    ]

是否可以根据关键字another_id将其划分为json数组。在这种情况下,应该像这样创建两个json数组

  jsonArr1 = [
          {id:1, another_id:1},
          {id:2, another_id:1}
        ]

  jsonArr2 = [
          {id:3, another_id:2}
        ]

another_id会有所不同。请帮帮我们

3 个答案:

答案 0 :(得分:2)

如果您不知道有多少不同的结果数组,则不应尝试为每个数组创建一个变量。而是将它们放在一个对象中,其中每个对象属性对应一个可能的another_id值,并且它的值是相应的数组。

您可以使用reduce

实现这一目标



var data = [{id:1, another_id:1},{id:2, another_id:1},{id:3, another_id:2}];

var result = data.reduce( (acc, obj) => {
    acc[obj.another_id] = acc[obj.another_id] || [];
    acc[obj.another_id].push(obj);
    return acc;
}, {});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:1)

如果您需要不同的变量,那么您可以构建一个函数,该函数将根据传递的值返回已过滤的数组。这将使用Array.filter()

function formatData(check) {
  var data = [{
      id: 1,
      another_id: 1
    },
    {
      id: 2,
      another_id: 1
    },
    {
      id: 3,
      another_id: 2
    }
  ];

  return data.filter(el => el.another_id === check);
}

jsonArr1 = formatData(1);
jsonArr2 = formatData(2);

console.log(jsonArr1);
console.log(jsonArr2);

答案 2 :(得分:0)

我希望下面的代码能为您效劳。因为这将为Location创建两个单独的json数组Arr1,为id创建Arr2

another_id