• 如何比较两个对象以确定第一个对象包含与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

  • 相关阅读:
    C语言从头学16——数据类型(二)
    Revit中“结构框架显示与剪切“的应用和一键剪切功能
    计算机网络-传输层
    nodejs+vue全国公考岗位及报考人数分析
    3个妙招,克服面试焦虑,紧张
    join、inner join、left join、right join、outer join的区别
    这才是老板爱看的人力资源分析报表,你只是在做“流水账”!
    C++string的使用
    Rust个人学习笔记2
    Python之pip命令指定安装源和版本
  • 原文地址:https://blog.csdn.net/qq_22182989/article/details/125496176