当其键与特定字符串匹配时,循环遍历Javascript对象的值

时间:2018-11-24 17:36:26

标签: javascript object key

我有一个循环遍历对象键的功能,直到键与输入中的关键字匹配为止。找到匹配项后,如何循环遍历匹配的对象键值?

let obj = {
  music: {
    "do you like music": "Yes I do",
    "what music do you like": "Jazz"
  },

  sports: {
    "Do you like sports": "Yes"
  }
};

let input = "i like music";

function run(input) {
  let newStr = input.split(' ');
  let key = Object.keys(obj);
  key.forEach((key) => {
    newStr.forEach((str) => {
      if (key === str) {
        console.log(key)
      }
    });
  });
};

run(input);

1 个答案:

答案 0 :(得分:1)

您可以使用main并从Array.flatMap返回匹配词value

我假设您想返回整个obj以匹配value

key