如何编写一个函数来返回数组中具有两个相同属性值的对象?

问题描述 投票:0回答:1

假设我有以下对象:

const myObjects = [
    { name: "Alice", age: 30 },
    { name: "Bob", age: 25 },
    { name: "Alice", age: 30 },
    { name: "David", age: 25 }
];

我编写了以下函数,以便在新数组中返回具有指定相同 props 的对象:

function findObjectsWithSameProperties(objects, property1, property2) {
  // Create an empty array to store the results
  const matchingObjects = [];

  // Loop through each object in the array
  for (const obj of objects) {
    // Check if the object has both specified properties
    if (obj.hasOwnProperty(property1) && obj.hasOwnProperty(property2)) {
      // Check if the values of the specified properties are the same
      if (obj[property1] === obj[property2]) {
        // If they are, add the object to the results array
        matchingObjects.push(obj);
      }
    }
  }

  // Return the array of matching objects
  return matchingObjects;
}

但是,当我期望它返回以下内容时,我的函数没有返回任何内容:

[
    { name: "Alice", age: 30 },
    { name: "Alice", age: 30 },
];

这是我调用该函数的方式:

findObjectsWithSameProperties(myObjects, "age", "name");

有人知道我做错了什么吗?这是 CodePen 链接:https://codepen.io/obliviga/pen/WNWNbMX?editors=0011

javascript arrays object properties
1个回答
0
投票

您正在循环遍历对象,检查它们是否具有两个 props,然后检查是否有

name === age
。这显然永远不会是真的。我建议添加您已经循环过的历史记录,然后比较它是否已经看到相同的对象。

function findObjectsWithSameProperties(objects, property1, property2) {
  // Create an empty array to store the results
  const matchingObjects = [];
  const seen = {};
  
  // Loop through each object in the array
  for (const obj of objects) {
    // Check if the object has both specified properties
    if (obj.hasOwnProperty(property1) && obj.hasOwnProperty(property2)) {
      const key = obj[property1] + '-' + obj[property2];
      // Check if we have seen this combination before
      if (seen[key]) {
        // Increment if it already exists
        seen[key].count++;
        // Add the object to the array of matching objects
        seen[key].objects.push(obj);
      } else {
        // If it's the first time it's ever seen this object, set count to 1
        seen[key] = { count: 1, objects: [obj] };
      }
    }
  }

  
  for (const key in seen) {
    if (seen[key].count > 1) {
      matchingObjects.push(...seen[key].objects); //count essentially keeps track of how many times it's already seen that object
    }
  }

  // Return the array of matching objects
  return matchingObjects;
}
© www.soinside.com 2019 - 2024. All rights reserved.