JavaScript中对象元素添加及复杂对象值存在性检测问题
Hey there! Let's break down your two JavaScript object-related questions one by one—this stuff can trip up new devs, so totally get where you're coming from.
Your current approach obj={programValue[i] : deviceValue[i]} has a small but critical issue: when defining dynamic keys in an object literal, you need to wrap the key expression in square brackets to tell JavaScript to evaluate it (instead of treating it as a literal string). Here's how to fix it:
Option 1: Create a new object with dynamic keys
Use computed property names (the square bracket syntax) to set the key dynamically:
// Example: if programValue[i] is "username" and deviceValue[i] is "john_doe" const obj = { [programValue[i]]: deviceValue[i] }; // Result: { username: "john_doe" }
Option 2: Add to an existing object (common for loops)
If you're building the object incrementally (like in a loop), don't reassign the entire object—instead, use bracket notation to set properties directly:
// Initialize empty object first const obj = {}; // Loop through your arrays to add pairs for (let i = 0; i < programValue.length; i++) { obj[programValue[i]] = deviceValue[i]; }
This works because obj[dynamicKey] tells JavaScript to use the value of dynamicKey as the property name, not the string "dynamicKey".
To handle nested objects and check for values that might be under different keys, you'll need a recursive approach to traverse all levels of the objects. Let's cover two scenarios: basic values and nested objects.
First: Helper function to traverse nested objects
This function will recursively collect all values from an object (including nested ones):
function getAllValues(obj) { const values = []; for (const key in obj) { if (obj.hasOwnProperty(key)) { const value = obj[key]; if (typeof value === 'object' && value !== null) { // Recurse if we hit a nested object/array values.push(...getAllValues(value)); } else { // Add basic values directly values.push(value); } } } return values; }
Scenario 1: Checking basic values (strings, numbers, booleans)
If obj1.app2 is a basic value, you can collect all values from obj2 and check if it's included:
// Get all values from obj2 const obj2AllValues = getAllValues(obj2); // Check if obj1.app2 exists in those values const valueExists = obj2AllValues.includes(obj1.app2);
Scenario 2: Checking nested objects (value is another object)
If obj1.app2 is a nested object, you need a deep comparison function to check if an identical object exists anywhere in obj2:
// Deep equality check for objects/arrays function deepEqual(a, b) { if (a === b) return true; if (a == null || typeof a !== 'object' || b == null || typeof b !== 'object') return false; const keysA = Object.keys(a); const keysB = Object.keys(b); if (keysA.length !== keysB.length) return false; for (const key of keysA) { if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false; } return true; } // Recursively check if target value exists in obj function doesValueExist(targetValue, obj) { for (const key in obj) { if (obj.hasOwnProperty(key)) { const currentValue = obj[key]; // Check if current value matches target if (deepEqual(currentValue, targetValue)) return true; // Recurse if current value is a nested object if (typeof currentValue === 'object' && currentValue !== null) { if (doesValueExist(targetValue, currentValue)) return true; } } } return false; } // Usage: Check if obj1.app2 exists in obj2 const target = obj1.app2; const nestedValueExists = doesValueExist(target, obj2);
This will work even if obj1.app2 is under a different key in obj2—it only cares about matching the value's content.
内容的提问来源于stack exchange,提问作者Amira Said

