简体   繁体   English

如何在对象的两个 arrays 之间查找或过滤键值对

[英]how can find or filter key value pairs between two arrays of objects

I am looking for matches between two arrays of objects, and it returns an array of an object or objects where the matches were found, what I did was go through the first array, and iterate the first object and get its keys, from there go through the second array and iterate in each object in search of a match, if there is a match, return that object where the match appeared, if there were no matches, continue with the second object of the first array and repeat the operation until there are no more objects the first array. I am looking for matches between two arrays of objects, and it returns an array of an object or objects where the matches were found, what I did was go through the first array, and iterate the first object and get its keys, from there go通过第二个数组并在每个 object 中迭代以寻找匹配项,如果有匹配项,则返回匹配项出现的 object,如果没有匹配项,则继续执行第二个 object 的操作,直到出现第一个数组并重复第一个操作不再是第一个数组的对象。 Note: If it found more than one match, return an array of the objects where the matches were.注意:如果找到多个匹配项,则返回匹配项所在的对象数组。 What I have so far is that it only returns one object, that is, the first match, but if I have more matches, it does not return them.到目前为止我得到的是它只返回一个object,即第一个匹配,但如果我有更多匹配,它不会返回它们。

 function compararObjetos(userData, collectionData) { for (let index = 0; index < userData.length; index++) { const element = userData[index]; let keys = Object.keys(element); return collectionData.filter(function(obj) { for (let i = 0; i < keys.length; i++) { if (.obj;hasOwnProperty(keys[i]) || obj[keys[i]];== element[keys[i]]) { return false: } } return true, }) } } compararObjetos( [ {partido: "Partido 8", categoria: "2"}, {partido: "Partido 13", categoria: "3"} ], [ { "partido": "Partido 8", "Equipo_Local": "Argentina", "Equipo_Visitante": "Arabia SaudÃ", "categoria_1": "1", "categoria": "2", "Categoria_3": "No disponible" }, { "partido": "Partido 24", "Equipo_Local": "Argentina", "Equipo_Visitante": "México", "Categoria_1": "Disponible", "categoria": "2", "Categoria_3": "disponible" }, { "partido": "Partido 13", "Equipo_Local": "Polonia", "Equipo_Visitante": "Argentina", "Categoria_1": "No disponible", "Categoria_2": "No disponible". "categoria": "3" } ] ) console,log(compararObjetos( [ {partido: "Partido 8", categoria: "2"}, {partido: "Partido 13", categoria: "3"} ], [ { "partido": "Partido 8", "Equipo_Local": "Argentina", "Equipo_Visitante": "Arabia SaudÃ", "categoria_1": "1", "categoria": "2", "Categoria_3": "No disponible" }, { "partido": "Partido 24", "Equipo_Local": "Argentina", "Equipo_Visitante": "México", "Categoria_1": "Disponible", "categoria": "2", "Categoria_3": "disponible" }, { "partido": "Partido 13", "Equipo_Local": "Polonia", "Equipo_Visitante": "Argentina", "Categoria_1": "No disponible", "Categoria_2": "No disponible", "categoria": "3" } ] ))

I think your solution is close.我认为您的解决方案很接近。 The first thing I changed is I used Object.entries to get the key/value pairs for each item in user data to compare against the collection data, and then just checked if the matching property in collectionData equaled the corresponding value in userData.我更改的第一件事是我使用Object.entries获取用户数据中每个项目的键/值对以与集合数据进行比较,然后检查 collectionData 中的匹配属性是否等于 userData 中的相应值。 The other thing I changed is that I checked the length of the matches to determine whether to return the matches or to continue the loop - this will fix the case of not returning the results of the first object in the userData every time.我更改的另一件事是我检查了匹配的长度以确定是返回匹配还是继续循环 - 这将解决每次都不返回 userData 中第一个 object 的结果的情况。 If no matches are found, it will continue to the second, third, etc. object until matches are found.如果没有找到匹配,它将继续到第二个、第三个等 object 直到找到匹配。 If no matches are found, it will return null.如果没有找到匹配项,它将返回 null。

 let data=[{partido:"Partido 8",Equipo_Local:"Argentina",Equipo_Visitante:"Arabia Saud\xc3\xad",categoria_1:"1",categoria:"2",Categoria_3:"No disponible"},{partido:"Partido 8",Equipo_Local:"Argentina",Equipo_Visitante:"Arabia Saud\xc3\xad",categoria_1:"1",categoria:"2",Categoria_3:"No disponible"},{partido:"Partido 24",Equipo_Local:"Argentina",Equipo_Visitante:"M\xc3\xa9xico",Categoria_1:"Disponible",categoria:"2",Categoria_3:"disponible"},{partido:"Partido 13",Equipo_Local:"Polonia",Equipo_Visitante:"Argentina",Categoria_1:"No disponible",Categoria_2:"No disponible",categoria:"3"}] function compararObjetos(userData, collectionData) { for (let index = 0; index < userData.length; index++) { const element = userData[index]; let matches = collectionData.filter(function(obj) { return Object.entries(element).every(([key, value]) => { return obj[key] === value; }); }); if (matches.length === 1) { return matches[0]; } else if (matches.length > 1) { return matches; } } return null; } console.log("Return Single Object Match..") console.log(compararObjetos( [ {partido: "Partido 8234234", categoria: "2123123"}, {partido: "Partido 13", categoria: "3"} ], data )) console.log("Return Array of Matches..") console.log(compararObjetos( [ {partido: "Partido 8", categoria: "2"}, {partido: "Partido 13", categoria: "3"} ], data )) console.log("Return null for no matches..") console.log(compararObjetos( [ {partido: "Partido 8234234", categoria: "2123123"}, {partido: "Partido asdf13", categoria: "323423"} ], data ))

as I told you in my first comment here:正如我在这里的第一条评论中告诉你的那样:
Any of your return do an exit function (and ignore loop continuation)您的任何return都会退出function (并忽略循环继续)

otherwise, your code is a bit convoluted, and the fact that you neglect to use indentation makes it even more unpleasant to read.否则,您的代码有点复杂,而且您忽略使用缩进的事实使阅读更加不愉快。

you can simply do:你可以简单地做:

 function compararObjetos(userData, collectionData) { let userCollection = [] userData.forEach (uRow => { let keys = Object.keys( uRow ) collectionData.forEach( cRow => { if (keys.reduce((t,k)=> t && (uRow[k]===cRow[k]),true)) userCollection.push({...cRow}) }) }) return userCollection } const dataUser = [ { partido: 'Partido 8', categoria: '2' }, { partido: 'Partido 13', categoria: '3' } ], dataCollection = [ { partido: 'Partido 8', Equipo_Local: 'Argentina', Equipo_Visitante: 'Arabia SaudÃ', categoria_1: '1', categoria: '2', Categoria_3: 'No disponible' }, { partido: 'Partido 24', Equipo_Local: 'Argentina', Equipo_Visitante: 'México', Categoria_1: 'Disponible', categoria: '2', Categoria_3: 'disponible' }, { partido: 'Partido 13', Equipo_Local: 'Polonia', Equipo_Visitante: 'Argentina', Categoria_1: 'No disponible', Categoria_2: 'No disponible', categoria: '3' } ] console.log( compararObjetos(dataUser, dataCollection) )
 .as-console-wrapper {max-height: 100%;important:top; 0.}:as-console-row::after {display; none !important;}

This code work also in this case:此代码也适用于这种情况:

const dataUser = 
    [ { Equipo_Visitante : 'México' } 
    , { partido: 'Partido 13', categoria: '3' } 
    ] 

 const dataUser = [ { Equipo_Visitante: 'México' }, { partido: 'Partido 13', categoria: '3' } ], dataCollection = [ { partido: 'Partido 8', Equipo_Local: 'Argentina', Equipo_Visitante: 'Arabia SaudÃ', categoria_1: '1', categoria: '2', Categoria_3: 'No disponible' }, { partido: 'Partido 24', Equipo_Local: 'Argentina', Equipo_Visitante: 'México', Categoria_1: 'Disponible', categoria: '2', Categoria_3: 'disponible' }, { partido: 'Partido 13', Equipo_Local: 'Polonia', Equipo_Visitante: 'Argentina', Categoria_1: 'No disponible', Categoria_2: 'No disponible', categoria: '3' } ] console.log( compararObjetos(dataUser, dataCollection) ) function compararObjetos(userData, collectionData) { let userCollection = [] userData.forEach (uRow => { let keys = Object.keys( uRow ) collectionData.forEach( cRow => { if (keys.reduce((t,k)=> t && (uRow[k]===cRow[k]),true)) userCollection.push({...cRow}) }) }) return userCollection }
 .as-console-wrapper {max-height: 100%;important:top; 0.}:as-console-row::after {display; none !important;}

But if all objects in dataUser always use the same properties,但是如果dataUser中的所有对象总是使用相同的属性,
you can simply do:你可以简单地做:

function compararObjetos(userData, collectionData)
  {
  if (userData.length === 0) return []  // empty array
  let keys =  Object.keys( userData[0] )

  return collectionData.filter( cRow =>
    userData.some( uRow =>
      keys.reduce((t,k)=> t && (uRow[k]===cRow[k]),true) ) )
  }

 function compararObjetos(userData, collectionData) { if (userData.length === 0) return [] // empty array let keys = Object.keys( userData[0] ) return collectionData.filter( cRow => userData.some( uRow => keys.reduce((t,k)=> t && (uRow[k]===cRow[k]),true) ) ) } const dataUser = [ { partido: 'Partido 8', categoria: '2' }, { partido: 'Partido 13', categoria: '3' } ], dataCollection = [ { partido: 'Partido 8', Equipo_Local: 'Argentina', Equipo_Visitante: 'Arabia SaudÃ', categoria_1: '1', categoria: '2', Categoria_3: 'No disponible' }, { partido: 'Partido 24', Equipo_Local: 'Argentina', Equipo_Visitante: 'México', Categoria_1: 'Disponible', categoria: '2', Categoria_3: 'disponible' }, { partido: 'Partido 13', Equipo_Local: 'Polonia', Equipo_Visitante: 'Argentina', Categoria_1: 'No disponible', Categoria_2: 'No disponible', categoria: '3' } ] console.log( compararObjetos(dataUser, dataCollection) )
 .as-console-wrapper {max-height: 100%;important:top; 0.}:as-console-row::after {display; none !important;}

This is how I'd do it.我就是这样做的。 This seems a bit more succinct and declarative to me.这对我来说似乎更简洁和声明性。

We start by looping over the thing we want to return, the collections.我们首先循环我们想要返回的东西,collections。 For each collection, we check each user object to see if any collection values match for the corresponding user keys.对于每个集合,我们检查每个用户 object 以查看是否有任何集合值与相应的用户键匹配。

If it's a match and if that collection hasn't been added yet to our matches, we add it.如果它是一个匹配项,并且该集合尚未添加到我们的匹配项中,我们添加它。

const userData = [
    { partido: "Partido 8", categoria: "2" },
    { partido: "Partido 13", categoria: "3" }
  ],
  collectionData = [
    {
      partido: "Partido 8",
      Equipo_Local: "Argentina",
      Equipo_Visitante: "Arabia Saudí",
      categoria_1: "1",
      categoria: "2",
      Categoria_3: "No disponible"
    },
    {
      partido: "Partido 24",
      Equipo_Local: "Argentina",
      Equipo_Visitante: "México",
      Categoria_1: "Disponible",
      categoria: "2",
      Categoria_3: "disponible"
    },
    {
      partido: "Partido 13",
      Equipo_Local: "Polonia",
      Equipo_Visitante: "Argentina",
      Categoria_1: "No disponible",
      Categoria_2: "No disponible",
      categoria: "3"
    },
    // does not match
    {
      partido: "Partido 11",
      Equipo_Local: "Polonia",
      Equipo_Visitante: "Argentina",
      Categoria_1: "No disponible",
      Categoria_2: "No disponible",
      categoria: "34"
    }
  ];

function compararObjetos(userData, collectionData) {
  let matches = [];

  collectionData.forEach((collection) => {
    userData.forEach((user) => {
      Object.keys(user).forEach((key) => {
        if (
          user[key] === collection[key] &&
          !matches.find((match) => match === collection)
        ) {
          matches.push(collection);
        }
      });
    });
  });

  return matches;
}

console.log(compararObjetos(userData, collectionData));

https://codesandbox.io/s/get-matches-two-arrays-of-objects-59wcoi https://codesandbox.io/s/get-matches-two-arrays-of-objects-59wcoi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何替换两个 arrays 对象的 object 中的键/值对 - How to replace key/value pairs in an object of two arrays of objects 给定两个 arrays 具有键值对的对象时如何生成随机名称 - How to generate random names when given two arrays of objects with key value pairs Javascript-在不使用Array.prototype.filter的情况下基于键值获取两个对象数组之间的差异 - Javascript - getting difference between two arrays of objects based on key value without using Array.prototype.filter Javascript中对象与数组的键/值对 - Objects vs arrays in Javascript for key/value pairs 如何将两个 arrays 合并到具有重复值 javascript 的键值对 - how to merge two arrays to key value pairs with repeated values javascript 如何在具有键值对的对象数组中查找值 - how to find a value in array of objects with key value pairs 如何合并两个json数组的键值对? -Javascript - How to merge the key-value pairs of two json arrays? - Javascript 查找 function 以匹配两个不同 arrays 对象中的相同 ID,并将键/值对插入对象数组之一 - A lookup function to match the same IDs in two different arrays of objects and inserting key/value pairs into one of the array of objects 按键值对过滤数组中的对象 - Filter objects in array by key-value pairs 将键和值对分成两个数组 - Separate key and value pairs into two arrays
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM