Created
September 25, 2018 01:24
-
-
Save tilersmyth/26984866d7428c9b502ec8971d961997 to your computer and use it in GitHub Desktop.
handle array validation based on specifications from another array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const userFields = [ | |
{ key: "name", value: "tyler" }, | |
{ key: "location", value: "boston" }, | |
{ key: "phone", value: "555-555-5555" }, | |
{ key: "email", value: "tyler@test.com" }, | |
{ key: "color", value: "red" }, | |
{ key: "sport", value: "golf" } | |
]; | |
const primaryFields = [ | |
{ key: "name", alias: ["nickname"], required: true }, | |
{ key: "address", alias: ["location", "homebase"], required: true }, | |
{ key: "age", alias: [], required: true }, | |
{ key: "phone", alias: [], required: false }, | |
{ key: "gender", alias: [], required: false } | |
]; | |
const missingFields = (fields, validFields) => { | |
return fields | |
.filter(({ required, key }) => { | |
return required && validFields.indexOf(key) < 0; | |
}) | |
.map(({ key }) => key); | |
}; | |
const secondaryFields = (primaryArr, allFields) => { | |
const primary = primaryArr.map(({ key }) => { | |
return key; | |
}); | |
return allFields.filter(({ key }) => { | |
return primary.indexOf(key) === -1; | |
}); | |
}; | |
const formatPrimaryFields = (primaryFields, allFields) => { | |
const allFieldsSize = allFields.length; | |
const output = { formatted: {}, fields: [] }; | |
for (let i = 0; i < allFieldsSize; i++) { | |
for (let p = 0; p < primaryFields.length; p++) { | |
if ( | |
allFields[i].key === primaryFields[p].key || | |
primaryFields[p].alias.indexOf(allFields[i].key) > -1 | |
) { | |
allFields[i].key = primaryFields[p].key; | |
output.formatted[allFields[i].key] = allFields[i].value; | |
if (allFields[i].value) { | |
output.fields.push(primaryFields[p].key); | |
} | |
} | |
} | |
} | |
return output; | |
}; | |
const primary = formatPrimaryFields(primaryFields, userFields); | |
const missing = missingFields(primaryFields, primary.fields); | |
const secondary = secondaryFields(primaryFields, userFields); | |
console.log("primary", primary.formatted); | |
console.log("missing", missing); | |
console.log("secondary", secondary); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment