• 如何比较两个对象以确定第一个对象包含与JavaScript中的第二个对象等效的属性值?


    给定两个对象 obj1 和 obj2,任务是检查 obj1 是否包含 JavaScript 中 obj2 的所有属性值。

    期望值:

     

    //输入:
    obj1: { name: "John", age: 23; degree: "CS" }
    //obj2: {age: 23, degree: "CS"}
           
    //输出: 
    true
    //输入: 
    obj1: { name: "John", degree: "CS" }
    obj2: {name: "Max", age: 23, degree: "CS"}
           
    //输出: 
    false

     

    为了解决这个问题,我们遵循以下方法。

    方法 1:解决这个问题是一种幼稚的方法。在此方法中,我们使用 for..在循环中和每次迭代中,我们检查两个对象的当前键是否相等,我们返回false,否则在完成循环后,我们返回true

    例:

    1. <script>
    2. // Define the first object
    3. let obj1 = {
    4. name: "John",
    5. age: 23,
    6. degree: "CS"
    7. }
    8. // Define the second object
    9. let obj2 = {
    10. age: 23,
    11. degree: "CS"
    12. }
    13. // Define the function check
    14. function check(obj1, obj2) {
    15. // Iterate the obj2 using for..in
    16. for (key in obj2) {
    17. // Check if both objects do
    18. // not have the equal values
    19. // of same key
    20. if (obj1[key] !== obj2[key]) {
    21. return false;
    22. }
    23. }
    24. return true
    25. }
    26. // Call the function
    27. console.log(check(obj1, obj2))
    28. </script>

    输出:

    true

    方法 2:在这种方法中,我们使用 Object.keys() 方法创建 obj2 所有键的数组,然后使用 Array.every() 方法检查 obj2 的所有属性是否都等于 obj1。

    例:

    1. <script>
    2. // Define the first object
    3. let obj1 = {
    4. name: "John",
    5. age: 23,
    6. degree: "CS"
    7. }
    8. // Define the Second object
    9. let obj2 = {
    10. age: 23,
    11. degree: "CS"
    12. }
    13. // Define the function check
    14. function check(obj1, obj2) {
    15. return Object
    16. // Get all the keys in array
    17. .keys(obj2)
    18. .every(val => obj1.hasOwnProperty(val)
    19. && obj1[val] === obj2[val])
    20. }
    21. // Call the function
    22. console.log(check(obj1, obj2))
    23. </script>

    输出:

    true

  • 相关阅读:
    从数字化到智能化再到智慧化,智慧公厕让城市基础配套更“聪明”
    宇视网络视频录像机添加摄像机提示离线
    chromium源码的下载与编译
    如何计算连续区间,字母分段
    实现表白墙
    Eclipse配置python环境全步骤
    江森自控×实在智能丨RPA一天完成20+人工作量,为制造业赋能
    一、根据系统架构定位系统性能瓶颈
    设计模式——责任链模式
    Java学习 --- 设计模式七大原则的依赖倒转原则
  • 原文地址:https://blog.csdn.net/qq_22182989/article/details/125496176