组织对象以在需要时创建键和/或将其他属性推入值对数组

时间:2018-11-25 00:51:16

标签: javascript arrays json sorting object

我试图实现的数据结构如下所示: 我希望list_id成为对象中的键,并保留具有匹配列表ID的所有ID。

var lists = { (list_id)1 : [1, 2, 3]
              (list_id)2 : [4, 5, 6]
              (list_id)3 : [7, 8, 9]
              (list_id)4 : [10, 11, 12] };

此对象是通过如下所示的json数据结构创建的:

    let json = [{ id: 1, list_id: 1 }, { id: 2, list_id: 1 }, 
                {id: 3, list_id: 1 }, {id: 4, list_id: 2 },
                {id: 5, list_id: 2 }, {id: 6, list_id: 2 },
                {id: 7, list_id: 3 }, {id: 8, list_id: 3 },
                {id: 9, list_id: 3 }, {id: 10, list_id: 4  },
                {id: 11, list_id: 4 }, {id: 12, list_id: 4 }]

我可以创建一个将所有list_id都保留为键的对象,但是在将actions_id推入具有匹配列表ID的值对数组中时遇到了麻烦。

 let listAll = {};

 json.forEach(function(lista, index, listb) {
   listAll[lista.list_id] = [];

   if ( listAll[lista.list_id] === lista.list_id){

      listAll[lista.list_id].push(lista.id)

    } else {

      listAll[lista.list_id] = [lista.id];

    }
});

我的目标是让和对象包含当前可从操作中获取的每个list_id的键。 然后将包含匹配list_id的每个动作添加到值对数组中。

此代码的当前输出为

{ '1': [ 3 ], '2': [ 6 ], '3': [ 9 ], '4': [ 12 ] }

它不包含所有数字,每个数组应包含3个数字。

2 个答案:

答案 0 :(得分:1)

一种替代方法是使用功能reduce按特定的key = ['list_id', list_id].join('')对对象进行分组。

let json = [{ id: 1, list_id: 1 }, { id: 2, list_id: 1 },                 {id: 3, list_id: 1 }, {id: 4, list_id: 2 },                {id: 5, list_id: 2 }, {id: 6, list_id: 2 },                {id: 7, list_id: 3 }, {id: 8, list_id: 3 },                {id: 9, list_id: 3 }, {id: 10, list_id: 4  },                {id: 11, list_id: 4 }, {id: 12, list_id: 4 }],
    result = json.reduce((a, {id, list_id}) => {
      let key = ['list_id', list_id].join(''); // For example: this is creating ['list_id', 1] to list_id1
      (a[key] || (a[key] = [])).push(id);
      return a;
    }, Object.create(null)/*This is only to create an object without prototype -> {}*/);

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

答案 1 :(得分:0)

您为什么不尝试使用hasOwnProperty呢?

var listAll = {};
json.forEach(function(list, index) {
  if (listAll.hasOwnProperty(list.list_id)) {
    listAll[list.list_id].push(list.id);
  }else {
    listAll[list.list_id] = [list.id];
  } 
});
console.log(listAll);