简体   繁体   中英

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. Going with the Object.keys route seems counterproductive, although that would easily allow me to filter out the correct names. 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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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