迭代数组并使用 AWS Lambda 函数进行答案验证

问题描述 投票:0回答:1

我是一名寻求指导的新开发者。我正在编写一个 AWS Lambda 函数用于数组验证。 假设我有第一个数组

{"food":"ribs", "snacks":"doritos", "drinks":"pepsi"} 

和第二个数组

{
  "answer": {
    "food": [
      "ribs",
      "pasta",
      "ramen"
    ],
    "snacks": [
      "doritos",
      "cheetos",
      "popcorn"
    ],
    "drinks": [
      "orange juice",
      "apple juice"
    ]
  }
}

如何使用第二个数组上的正确答案对第一个数组进行验证?

验证应返回 {"true","true","false"}

我对如何开始/采取什么方法感到困惑

如有任何建议,我们将不胜感激

javascript arrays validation aws-lambda matching
1个回答
0
投票

您需要找到答案键并使用

hasOwnProperty()
功能进行检查,如下所示:

function validateArray(firstArray, secondArray) {
    const validationResults = [];

    // iterate through the keys in the first array
    for (const key in firstArray) {
        // Check if the key is present in the second array
        if (secondArray.answer.hasOwnProperty(key)) {corresponding array of the second array
            const validationResult = secondArray.answer[key].includes(firstArray[key]);
            validationResults.push(validationResult);
         } else {
             validationResults.push(false);
         }
     }

     return validationResults;
}

// as you provided
const firstArray = {"food": "ribs", "snacks": "doritos", "drinks": "pepsi"};
const secondArray = {
    "answer": {
        "food": ["ribs", "pasta", "ramen"],
        "snacks": ["doritos", "cheetos", "popcorn"],
        "drinks": ["orange juice", "apple juice"]
    }
};

const result = validateArray(firstArray, secondArray);
console.log(result); // as you need the output is [true, true, false]
© www.soinside.com 2019 - 2024. All rights reserved.