JavaScript中如何在对象数组里通过if语句匹配field_id并返回对应值
value when field_id equals 40 from an array of objects? Hey there! Let's figure out how to get that specific value you need. You've got an array of objects, and you want to pull the value where field_id is 40 (which is 111 in your example). Here are a few simple, common ways to do this in JavaScript:
Method 1: Use Array.prototype.find() (Recommended)
This is the cleanest and most efficient approach because find() stops traversing the array as soon as it finds the first matching item.
const myObj = [ { id: 11, company_id: 1, field_id: 7, value: 700 }, { id: 12, company_id: 1, field_id: 40, value: 111 }, { id: 13, company_id: 1, field_id: 41, value: 222 } ]; // Find the first object where field_id is 40 const matchingItem = myObj.find(item => item.field_id === 40); // Safely get the value (in case no match is found) const targetValue = matchingItem ? matchingItem.value : undefined; console.log(targetValue); // Output: 111
We add a check for matchingItem to avoid errors if there's no object with field_id: 40 in the array.
Method 2: Use a forEach Loop
If you need to do extra processing while traversing the array, a forEach loop works well:
const myObj = [ { id: 11, company_id: 1, field_id: 7, value: 700 }, { id: 12, company_id: 1, field_id: 40, value: 111 }, { id: 13, company_id: 1, field_id: 41, value: 222 } ]; let targetValue; myObj.forEach(item => { if (item.field_id === 40) { targetValue = item.value; // Skip remaining iterations once we find the match return; } }); console.log(targetValue); // Output: 111
Method 3: Use Array.prototype.filter()
This is useful if you might have multiple objects with field_id: 40—it returns all matching items in an array:
const myObj = [ { id: 11, company_id: 1, field_id: 7, value: 700 }, { id: 12, company_id: 1, field_id: 40, value: 111 }, { id: 13, company_id: 1, field_id: 41, value: 222 } ]; // Get all objects where field_id is 40 const matchingItems = myObj.filter(item => item.field_id === 40); // If there's at least one match, grab the first item's value const targetValue = matchingItems.length > 0 ? matchingItems[0].value : undefined; console.log(targetValue); // Output: 111
Quick Note
Unless you expect multiple matching objects, find() is the best choice—it's faster and more concise for single-match scenarios.
内容的提问来源于stack exchange,提问作者Lizz Parody

