javascript - 组织对象以在需要时创建键和/或将不同的属性推送到值对数组

标签 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 个数字。

最佳答案

另一种方法是使用函数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; }

关于javascript - 组织对象以在需要时创建键和/或将不同的属性推送到值对数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53463756/

相关文章:

javascript - for (var o in this) 在对象内部

android - 从 JSON Android 获取数据

javascript - 检查是否存在并从返回的 JSON 中删除表行

javascript - file.txt 中的 PHP Like 按钮计数器

javascript - react 导航 : Detect to which screen the app was navigated

javascript - 如何解决在 body 选择器后立即创建羽毛光 div-s 的问题?

c++ - 在 C++ 中选择运行时数组或 vector

arrays - 从另一组范围中切出一组整数范围

java - 如何将: (method Array) becomes original Array modified by method,和原来的Array变成(方法Array)

javascript - 如何使用 angular.js $http 服务在 PHP 后端 API 中实现 'hit' 特定功能?