基于其他JSON对象值关联对应类型JSON对象的技术咨询
Got it, let's break this down into a clean, scalable solution—perfect for when you have lots of Type objects to work with. Here's how to implement it in JavaScript:
Step 1: Organize Your Type Objects into a Lookup Collection
First, instead of keeping your TypeA/TypeB/TypeC as separate variables, store them in a structured collection so you can easily iterate through them later. This makes adding new types way simpler:
// Store all Type objects in an array for flexible iteration const allTypes = [ { name: "TypeA", ...TypeA }, { name: "TypeB", ...TypeB }, { name: "TypeC", ...TypeC } ]; // Optional: Use an object for direct name-based access if needed const typeMap = { TypeA, TypeB, TypeC };
Step 2: Create a Custom Matching Function
Next, write a function that takes your "actual data" JSON object and returns the matching Type object. You can tweak the logic to match on whatever properties matter to you—here are two common scenarios:
Example 1: Exact Match on All Properties
If you need to match every property (length, width, color) exactly:
function findMatchingType(actualData) { return allTypes.find(type => { return type.length === actualData.length && type.width === actualData.width && type.color === actualData.color; }); }
Example 2: Match on Specific Properties
If you only care about matching length and width (ignoring color):
function findMatchingType(actualData) { return allTypes.find(type => { return type.length === actualData.length && type.width === actualData.width; }); }
Step 3: Use the Function with Your Actual Data
Call the function with your real data to get the target Type object:
// Example actual data const actualData = { "length": "150", "width": "120", "color": "#4202f4" }; const matchedType = findMatchingType(actualData); console.log(matchedType); // Outputs TypeC's object
Edge Case Handling
- If no match is found, the function returns
undefined—add a fallback to handle this gracefully:function findMatchingType(actualData) { const match = allTypes.find(...); return match || { error: "No matching type found" }; } - If multiple Type objects share the same properties,
find()returns the first match. Usefilter()instead if you need all matching objects.
内容的提问来源于stack exchange,提问作者CrazyCoder

