gpt4 book ai didi

javascript - 如何使用 angular6 根据 id 值在第一个数组对象中添加第二个数组对象?

转载 作者:行者123 更新时间:2023-12-01 01:41:00 24 4
gpt4 key购买 nike

这是我的代码

categories = [{"id":"101","name":"category1"},{"id":"102","name":"category2"},{"id":"103","name":"category3"},{"id":"104","name":"category4"}];

actions = [{"id":"201","name":"action1","category_id":"101"},{"id":"202","name":"action2","category_id":"101"},{"id":"203","name":"action3","category_id":"102"},{"id":"204","name":"action4","category_id":"104"}];

在上面的categories数组中,id值存在于actions数组中。所以我想将两个数组合并成一个数组,如下输出。

输出:-

finalList = [{"id":"101","name":"category1","actions":[{"id":"201","name":"action1","category_id":"101"},{"id":"202","name":"action2","category_id":"101"}]},{"id":"102","name":"category2","actions":[{"id":"203","name":"action3","category_id":"102"}]},{"id":"103","name":"category3","actions":[]},{"id":"104","name":"category4","actions":[{"id":"204","name":"action4","category_id":"104"}]}]

最佳答案

对于每个类别查找操作元素并将其添加到类别对象

this.categories.forEach((element) => {
element['actions'] = this.actions.filter((data) => data.category_id === element.id);
});
console.log(this.categories);

关于javascript - 如何使用 angular6 根据 id 值在第一个数组对象中添加第二个数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52418596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com