将值从一个对象匹配到另一个

时间:2018-10-16 00:07:03

标签: javascript arrays json for-loop key-value

我有两个对象数组:

[ 
  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 ... keys的任何值匹配,然后进行设置一个变量,直到匹配记录中的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]));
}

但是那又使我得到了一个数组数组,基本上使我回到了相同的情况。我的大脑炸得很厉害,诚然有一个循环弱点。谁能给我示范完成我需要的体面的方式?

3 个答案:

答案 0 :(得分:1)

您可以先收集要测试的值,然后使用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)));

答案 1 :(得分:1)

您似乎必须将一个数组中的每个对象与另一个数组中的每个对象的键进行比较。最初的暴力破解方法有3个嵌套的for循环:

// Loop through the objects in the first array
for (const objectA of arrayA) {

  // Loop through that object's keys
  for (const key in objectA) {

    // Loop through the objects in the second array
    for (const objectB of arrayB) {

      if (objectA[key] === objectB.key_value) {
        // do all the stuff
      }
    }
  }
}

答案 2 :(得分:0)

这就是我最后要做的,只是留下一个记录:)

let stopRules = pd.stopRules;
let pdSegs = pd.segs;
let routeStopsTest = [];

//Returns a flat array of all unique values in first object
//Thanks @slider!
let pdSegValues = Array.from(pdSegs.reduce((acc, curr) => {
  Object.values(curr).forEach(v => acc.add(v));
  return acc;
}, new Set()));

//Pushes all objects from stopRules array to a holding array
//When they match individual segments in the pdSegs array
pdSegValues.forEach( seg => {
  let nullTest = stopRules.filter(o => o.key_value === seg);
  if(nullTest.length !== 0){
    routeStopsTest.push(nullTest);
  }else{}
});

然后我要做的就是将结果对象数组展平,然后得到所需的结果,然后可以为原始目的循环遍历。

谢谢大家,我们的见解深刻。我在这里学到了很多:)

相关问题