我有一个包含团队成员的对象。
如果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 :(得分:1)
逻辑向后......您需要检查消息中是否存在密钥,而不是相反。
类似的东西:
Object.keys(team).forEach(function(key) {
if (incomingMessage.indexOf(key) > -1){
console.log('Found ' + key +' in message')
}
});
答案 1 :(得分: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
}
}
答案 2 :(得分:0)
var arrRecTeam = incomingMessage.split(' ');
var arrTeam = Object.keys(team)
arrTeam.forEach((val, key) => console.log("found at", arrRecTeam.indexOf(val)))
答案 3 :(得分:0)
您的逻辑是相反的,您需要查找字符串中的键,而不是键中的字符串。
angular.module('App', [])
.directive('dir', function () {
return {
restrict: 'E',
template: `
<div ng-transclude="header"></div>
<div class="static-content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
<div ng-transclude="footer">
`,
transclude: {
'header': '?dirHeader',
'footer': '?dirFooter'
},
link: function ($s, $el, $attrs, thisCtrl, $transclude) {
console.log($transclude.isSlotFilled('header'))
console.log($transclude.isSlotFilled('footer'))
}
};
});
&#13;
答案 4 :(得分: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'
}