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

例:

<script>

	// Define the first object
	let obj1 = {
		name: "John",
		age: 23,
		degree: "CS"
	}

	// Define the second object
	let obj2 = {
		age: 23,
		degree: "CS"
	}

	// Define the function check
	function check(obj1, obj2) {

		// Iterate the obj2 using for..in
		for (key in obj2) {
			
			// Check if both objects do
			// not have the equal values
			// of same key
			if (obj1[key] !== obj2[key]) {
				return false;
			}
		}
		return true
	}

	// Call the function
	console.log(check(obj1, obj2))
</script>

输出:

true

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

例:

<script>

	// Define the first object
	let obj1 = {
		name: "John",
		age: 23,
		degree: "CS"
	}

	// Define the Second object
	let obj2 = {
		age: 23,
		degree: "CS"
	}

	// Define the function check
	function check(obj1, obj2) {
		return Object

			// Get all the keys in array
			.keys(obj2)
			.every(val => obj1.hasOwnProperty(val)
				&& obj1[val] === obj2[val])
	}

	// Call the function
	console.log(check(obj1, obj2))
</script>

输出:

true

猜你喜欢

转载自blog.csdn.net/qq_22182989/article/details/125496176