2017-04-14 43 views
-1

我有一个包含团队成员的对象。在Object.keys中获得匹配键(obj)

如果incomingMessage包含其中一个键,那么我想返回其中的一条消息。

有没有一种方法可以在下面的代码中获得匹配的密钥?

const team = { 
 
    hank: ['good guy', 'wonderful man'], 
 
    chuck: ['jerk', 'buttmunch'] 
 
} 
 

 
let incomingMessage = 'tell me about chuck'; 
 

 
if(Object.keys(team).indexOf(incomingMessage) > -1) { 
 
    console.log(team); 
 
    //is there a way here that I can get the 
 
    //key that has matched? so in this case, 'chuck' 
 
}

+0

您将需要寻找消息中的关键,而不是在密钥的消息。 – epascarello

+0

这样做会更有意义:直接循环:对于每个密钥,如果密钥在消息中,则显示结果。或者你可以写一些东西来解析消息中的名字,然后它只是一个关键的查找。 – jonrsharpe

回答

1

逻辑是倒退......你需要检查,如果该键的消息中存在,而不是周围的其他方式。

喜欢的东西:

Object.keys(team).forEach(function(key) { 
    if (incomingMessage.indexOf(key) > -1){ 
     console.log('Found ' + key +' in message') 
    } 
}); 
0

我会用for in循环来接手球队的属性,然后在它使用indexOf

const team = { 
    hank: ['good guy', 'wonderful man'], 
    chuck: ['jerk', 'buttmunch'] 
} 

let incomingMessage = 'tell me about chuck'; 

for (var member in team) { 
    if (incomingMessage.indexOf(member) > -1) { 
     console.log(team[member]); // your team member information array 
} 
} 
0
var arrRecTeam = incomingMessage.split(' '); 
var arrTeam = Object.keys(team) 


arrTeam.forEach((val, key) => console.log("found at", arrRecTeam.indexOf(val))) 
0

你的逻辑是相反的,你需要寻找字符串中的关键,而不是在关键的字符串。

const team = { 
 
    hank: ['good guy', 'wonderful man'], 
 
    chuck: ['jerk', 'buttmunch'] 
 
} 
 

 
const msgCheck = (msg) => Object.keys(team).filter((k) => msg.indexOf(k) > -1) 
 

 
console.log(msgCheck('tell me about chuck')) 
 
console.log(msgCheck('tell me about hank')) 
 
console.log(msgCheck('tell me about chuck and hank'))

0

const team = { 
 
    hank: ['good guy', 'wonderful man'], 
 
    chuck: ['jerk', 'buttmunch'] 
 
} 
 

 
var incomingMessage = 'tell me about chuck'; 
 

 
if(incomingMessage.indexOf(Object.keys(team)) > -1) { 
 
    alert(team); 
 
    //is there a way here that I can get the 
 
    //key that has matched? so in this case, 'chuck' 
 
}