javascript - 如何使用js比较数组并创建最终数组?
问题描述
我有两个对象数组:
对象 1:
[
{
"id":"30772",
"posimage":"/b/l/blue-shirt_1_1.jpg",
"position":"Position Chest",
"tech":"Embroidery"
},
{
"id":"30772",
"posimage":"/b/l/blue-shirt_1_1.jpg",
"position":"Position Chest",
"tech":"Screenprint Textile"
},
{
"id":"30772",
"posimage":"/b/l/blue-shirt_1_1.jpg",
"position":"Position Arm Left",
"tech":"Embroidery"
},
{
"id":"30772",
"posimage":"/b/l/blue-shirt_1_1.jpg",
"position":"Position Arm Left",
"tech":"Screenprint Textile"
}
]
对象 2:[
{
"sku":"30772", "qty":"1" }, {
"position":"Position Arm Left", "tech":"刺绣" }, {
"position":"Position Chest ", "tech":"Screenprint Textile" } ]
对象 2:
[
{
"position":"Position Arm Left",
"tech":"Embroidery"
},
{
"position":"Position Chest",
"tech":"Screenprint Textile"
}
]
我需要比较对象参数,即位置和技术,并需要获得最终数组,其中该位置和对象可用,如下所示
最终输出:
[
{
"id":"30772",
"posimage":"/b/l/blue-shirt_1_1.jpg",
"position":"Position Chest",
"tech":"Screenprint Textile"
},
{
"id":"30772",
"posimage":"/b/l/blue-shirt_1_1.jpg",
"position":"Position Arm Left",
"tech":"Embroidery"
}
]
解决方案
如果你使用 lodash 那么你可以使用intersectionWith
方法,因为你想要基于两个键的交叉是直观的。
const object1 = [
{
id: "30772",
posimage: "/b/l/blue-shirt_1_1.jpg",
position: "Position Chest",
tech: "Embroidery"
},
{
id: "30772",
posimage: "/b/l/blue-shirt_1_1.jpg",
position: "Position Chest",
tech: "Screenprint Textile"
},
{
id: "30772",
posimage: "/b/l/blue-shirt_1_1.jpg",
position: "Position Arm Left",
tech: "Embroidery"
},
{
id: "30772",
posimage: "/b/l/blue-shirt_1_1.jpg",
position: "Position Arm Left",
tech: "Screenprint Textile"
}
];
const object2 = [
{
position: "Position Arm Left",
tech: "Embroidery"
},
{
position: "Position Chest",
tech: "Screenprint Textile"
}
];
const result = _.intersectionWith(
object1,
object2,
(o1, o2) => o1.position === o2.position && o1.tech === o2.tech
);
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
推荐阅读
- javascript - 通过 JavaScript 控制台查找项目时遇到问题
- numpy - 如何切换阵列轴?
- sql - 如何从返回多个重复记录的查询中选择唯一行?
- python - scipy.stats cdf 大于 1
- r - case_when 在多个条件下中断
- python-3.x - python3:如何将代码直接粘贴到调用函数的控制台中,而不必加载 .py 文件?
- cloud-foundry - PCF Config Server 定期刷新配置?
- python - 如何在列表末尾获取某些值,每隔一段时间获取这些值,并在 Python 中的原始列表中插入某些位置?
- flutter - 我使用flutter_modular,我需要动态创建自定义转换。我怎么能做到这一点?
- javascript - 使用 darge-d3 的可折叠力布局