我是一名寻求指导的新开发者。我正在编写一个 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"}
我对如何开始/采取什么方法感到困惑
如有任何建议,我们将不胜感激
您需要找到答案键并使用
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]