You cannot create an array called companies that reference variable names* as they do not mean anything to the interpreter. Instead, create a mapping of companies.
var data = [ 'Joe', 'Peter', '12345', 'programmer' ];
var companies = {
'xyz' : [ 'programmer', 'HR','Tester' ],
'abc' : [ 'HR', 'Tester' ],
'def' : [ 'programmer', 'HR,Tester' ]
};
function create(empData) {
var employee = {
firstName : empData[0],
lastName : empData[1],
phone : empData[2]
};
var ocupation = empData[3];
for (var company in companies) {
employee[company] = companies[company].indexOf(ocupation) > -1 ? 'checked' : 'unchecked';
}
return employee;
}
document.getElementsByTagName('body')[0].innerHTML = JSON.stringify(create(data), undefined, ' ');
body {
white-space: pre;
font-family: monospace;
}
Result
{
"firstName": "Joe",
"lastName": "Peter",
"phone": "12345",
"xyz": "checked",
"abc": "unchecked",
"def": "checked"
}
Notes
* If that array contains strings, as I assume that is what you are attempting to do, then this is not possible; but if you are referencing them by their variable reference, and not the string name, then you need to define the variables first.
Not Valid
You cannot reference a variable without scope.
var companies = ["xyz", "abc", "def"];
var xyz = ["Programmer", "HR", "Tester"];
var abc = ["HR", "Tester"];
var def = ["Programmer", "HR", "Tester"];
Not Valid
You cannot reference a variable that has not been defined.
var companies = [xyz, abc, def];
var xyz = ["Programmer", "HR", "Tester"];
var abc = ["HR", "Tester"];
var def = ["Programmer", "HR", "Tester"];
Valid
This creates a 2-dimensional array, but you don't know which company you are referring to, because there is not object-key relationship.
var xyz = ["Programmer", "HR", "Tester"];
var abc = ["HR", "Tester"];
var def = ["Programmer", "HR", "Tester"];
var companies = [xyz, abc, def];