从数组中检索元素,其元素是javascript中的对象

时间:2015-11-20 08:42:34

标签: javascript javascript-objects

我有两个数组变量,其中每个元素都是一个具有如下属性的对象:

var employees = [{
                 name: 'Jack',
                 empId: 0,
                 age: 25,
                 orgId: 1
                 }, {
                 name: 'Lucifer', 
                 empId: 1,
                 age: 35,
                 orgId: 2
                 }, {
                 name: 'Adam',
                 empId: 3,
                 age: 46,
                 orgId: 1
                 }, {
                 name: 'Eve',
                 empId: 4,
                 age: 30,
                 orgId: 3
               }];

,第二个变量是

var companies= [{
 name: 'Microsoft',
 id: 1,
 employees: [5 , 9]
}, {
 name: 'Google',
 id: 2,
 employees: [1]
}, {
 name: 'LinkedIn',
 id: 3,
 employees: [10]
}];

所以现在我希望当我提供公司名称(例如:Google)时,它会返回员工详细信息。我想通过使用filter()/ reduce()方法来做到这一点,但我无法做到这一点。需要帮助..谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用forEach循环并检查名称:

var Employees = []; //initialize  
companies.forEach(function(company) {
    if (company.name == "Microsoft"){
        Employees = company.employees;
        //whatever you like
        Employees.forEach(function(id){
              alert(id);
        });

    }
});

工作JsFiddle:https://jsfiddle.net/sapyt777/

答案 1 :(得分:1)

如果员工function unserializePhp($sessionData) { $returnData = array(); $offset = 0; while ($offset < strlen($sessionData)) { if (!strstr(substr($sessionData, $offset), '|')) { throw new Exception('invalid data, remaining: ' . substr($sessionData, $offset)); } $pos = strpos($sessionData, '|', $offset); $num = $pos - $offset; $varname = substr($sessionData, $offset, $num); $offset += $num + 1; $data = unserialize(substr($sessionData, $offset)); $returnData[$varname] = $data; $offset += strlen(serialize($data)); } return $returnData; } 与公司orgId相同,则可以使用filter;一个获取id,然后另一个获取与该ID相关联的员工。该函数返回一组员工。

id

输出

function getEmployees(company) {
  var id = companies.filter(function (el) {
      return el.name === company;
  })[0].id;
  return employee.filter(function (el) {
      return el.orgId === id;
  });
}

getEmployees('Microsoft');

DEMO

答案 2 :(得分:0)

试图提升我的技能。所以我很确定它有效,但我不知道它是否是实现你想要的好方法!

var input = "Microsoft";

for(company in companies) {
    if(companies[company].name === input) {
        for(emp in employee) {
            if(companies[company].id === employee[emp].orgId)
            {
                console.log(employee[emp]);
            }
        }
    }
}