js loops an object property and extracts the value inside, enters a character to fuzzily query whether the key in the object contains this character, if so, extracts the value of this key and forms an array

Ok, here is a sample code based on the JavaScript language:

// 初始化一个包含键值对的对象
const obj = {
    
    
  name: "John",
  age: 30,
  city: "New York",
  country: "USA",
  occupation: "Developer"
};

// 定义一个函数,输入查询字符和对象,返回匹配的键的值组成的数组
function searchObject(query, object) {
    
    
  const result = [];
  for (const key in object) {
    
    
    if (object.hasOwnProperty(key) && key.includes(query)) {
    
    
      result.push(object[key]);
    }
  }
  return result;
}

// 使用函数搜索匹配的值
const query = "o";
const resultArray = searchObject(query, obj);

// 输出结果
console.log(resultArray);

In this sample code, we first define an object obj that contains key-value pairs. We then define a function called searchObject that takes a query string and an object as arguments, iterates over all keys of the object, and adds the value of the key containing the query string to the resulting array. Finally, we call the function and save the result in the resultArray variable and output it to the console.
-
Note that since object properties in JavaScript have no fixed order, the order of the values ​​in the resulting array may differ from the order of the key-value pairs in the object.

ChatGPT is really good to know after using it

insert image description here
Although the code is simple, you can copy it directly after waiting for a minute. Convenient

Guess you like

Origin blog.csdn.net/qq_51055690/article/details/129128343