简体   繁体   English

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

[英]retrieving the elements from array whose elements are objects in javascript

i have two arrays variables in which each element is an object having some properties like this :我有两个数组变量,其中每个元素都是一个具有以下属性的对象:

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
               }];

and the second variable is第二个变量是

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

so now i want that when i give a company name (for example: Google),then it will return the employee details.所以现在我希望当我给出公司名称(例如:Google)时,它将返回员工详细信息。 i want to do it by using filter()/reduce() method, but i am not able to do it .我想通过使用 filter()/reduce() 方法来做到这一点,但我无法做到。 Help needed .. thank you需要帮助..谢谢

You can do that with a forEach loop and checking the name:您可以使用forEach循环并检查名称来做到这一点:

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

    }
});

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

If the employee orgId is the same as the company id you can use filter ;如果员工orgId与公司id相同,则可以使用filter one to get the id , and then another to grab the employees associated with that id.一个获取id ,然后另一个获取与该 ID 关联的员工。 The function returns an array of employees.该函数返回一个雇员数组。

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');

OUTPUT输出

[
  {
    "name": "Jack",
    "empId": 0,
    "age": 25,
    "orgId": 1
  },
  {
    "name": "Adam",
    "empId": 3,
    "age": 46,
    "orgId": 1
  }
]

DEMO演示

Trying to brush-up my skills.试图提高我的技能。 So I'm pretty sure it works but I don't know if it's a good way to achieve what you want!所以我很确定它有效,但我不知道这是否是实现你想要的好方法!

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]);
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM