简体   繁体   English

Javascript从数组和对象键中查找组合的属性

[英]Javascript finding combined properties from an array and object keys

I have an object. 我有一个对象。 I would like to be able to dynamically create an array, then create another object that contains the key-value pairs that correspond with properties from the array that I created. 我希望能够动态创建一个数组,然后创建另一个对象,该对象包含与我创建的数组中的属性相对应的键值对。

For example, if I have the following object... 例如,如果我有以下对象...

var churchMembers = {
  John: 'fsiolfjdklsjds@yahoo.com',
  Betty: 'fowifj@hotmail.com',
  Christopher: 'fsis@yahoo.com',
  James: 'wfowji@gmail.com',
  Deep: 'abab@msn.com'
};

and I create the following array: 然后创建以下数组:

var peopleComing = ['John', 'Christopher', 'James'];

I want the following response 我想要以下回应

var peopleList = {
  John: 'fsiolfjdklsjds@yahoo.com',
  Christopher: 'fsis@yahoo.com',
  James: 'wfowji@gmail.com'
};

Right now I'm trying to use a for loop and all I'm doing is iterating through the object properties, which is not giving me anything. 现在,我正在尝试使用for循环,而我正在做的就是遍历对象属性,这没有给我任何东西。 Going with the Object.keys route seems counterproductive, although that would easily allow me to filter out the correct names. 使用Object.keys路由似乎适得其反,尽管这很容易使我过滤出正确的名称。 Thanks. 谢谢。 SIAP 亚太统计所

You can use Array#forEach to iterate over your list of names, and get the email for each name and add it to your peopleList . 您可以使用Array#forEach遍历名称列表,并获取每个名称的电子邮件并将其添加到peopleList

var peopleList = {};

peopleComing.forEach(function(name){
    peopleList[name] = churchMembers[name];
});

Ignoring the typo you have in your code, the below code should be capable of initializing peopleList with what you want. 忽略代码中的拼写错误,以下代码应能够使用所需的内容初始化peopleList

var churchMembers = {
  John: "fsiolfjdklsjds@yahoo.com"
  Betty: "fowifj@hotmail.com",
  Christopher: "fsis@yahoo.com",
  James: "wfowji@gmail.com",
  Deep: "abab@msn.com"
},

peopleComing = ["John", "Christopher", "James"],

peopleList = {};

for (var i = 0, j = peopleComing.length; i < j; i++) {
  peopleList[peopleComing[i]] = churchMembers[peopleComing[i]];
}

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

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