我试图实现的数据结构如下所示: 我希望 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/