You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于其他JSON对象值关联对应类型JSON对象的技术咨询

Solution for Matching Target JSON Objects Based on Another JSON's Values

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. Use filter() instead if you need all matching objects.

内容的提问来源于stack exchange,提问作者CrazyCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:32:48