gpt4 book ai didi

javascript - 将一个对象的值匹配到另一个对象

转载 作者:行者123 更新时间:2023-12-01 01:35:54 25 4
gpt4 key购买 nike

我有两个对象数组:

[ 
0: {key1: value1, key2: value2, key3: value3},
1: {key1: value1, key2: value2, key3: value3}
]

[
0: {stop_id: 173, file_id: "1", key_type: null, key_value: "0020", seg_beg: 32},
1: {stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10},
2: {stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10}
]

我需要检查第一个对象中任何键的值是否与第二个对象中key_value...键的任何值匹配,然后设置一个变量,直到匹配记录中的 stop_id 值。像这样:

if(object1.value === object2.key_value){
match = object2[iterator].stop_id;
}

为了简化这一点,我尝试只获取第一个对象的值:

//pd.segs is object 1
let pdSegValues = [];

for(let i=0;i<pd.segs.length;i++){
pdSegValues.push(Object.values(pd.segs[i]));
}

但这又让我得到了一个数组,基本上让我回到了同样的情况。我的大脑很糟糕,而且不可否认的是,我对循环有弱点。谁能告诉我一种体面的方法来完成我在这里需要的事情?

最佳答案

您可以通过收集要测试的值然后使用 some 来完成此操作.

let arr1 = [
{"a1": "value1", "b1": "value2"},
{"a2": "0020", "b2": "value22"},
{"a3": "value111", "b3": "0201"}
];

let arr2 = [
{stop_id: 173, file_id: "1", key_type: null, key_value: "0020", seg_beg: 32},
{stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10},
{stop_id: 176, file_id: "1", key_type: null, key_value: "0201", seg_beg: 10}
];

// accumulate unique arr1 values to an array
let arr1Values = Array.from(arr1.reduce((acc, curr) => {
Object.values(curr).forEach(v => acc.add(v));
return acc;
}, new Set()));

// accumulate all unique arr2 "key_value"
let arr2KeyValues = arr2.reduce((acc, curr) => {
acc.add(curr.key_value);
return acc;
}, new Set());

console.log(arr1Values);
console.log(Array.from(arr2KeyValues));

// Test if any of the values in objects in the first array are
// equal to any of the key_values in the second array
console.log(arr1Values.some(k => arr2KeyValues.has(k)));

关于javascript - 将一个对象的值匹配到另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826268/

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