如何从特定字符串过滤器上的对象中提取键值对?

时间:2020-07-07 08:48:16

标签: javascript

const obj = {
"pi_diagram": null,
"painting": null,
"heat_treatment": null,
"welding_procedure": null,
"inspection_test": null,
"pipecl_hadoop": null,
"pipecl": null,
"ludo_min_hadoop": null,
"ludo_min": 4,
"ludo_normal_hadoop": null,
"ludo_normal": 6,
"ludo_max_hadoop": null,
"ludo_max": null,
"ludo_test": null,
"ludo_mech_min": null,
"ludo_mech_max": null,
"ludo_unit": "barg",
"temp_min_hadoop": null

}

我有这个对象,如何提取在键中附加了'_hadoop'的键值对?

3 个答案:

答案 0 :(得分:1)

const obj = {
  "pi_diagram": null,
  "painting": null,
  "heat_treatment": null,
  "welding_procedure": null,
  "inspection_test": null,
  "pipecl_hadoop": null,
  "pipecl": null,
  "ludo_min_hadoop": null,
  "ludo_min": 4,
  "ludo_normal_hadoop": null,
  "ludo_normal": 6,
  "ludo_max_hadoop": null,
  "ludo_max": null,
  "ludo_test": null,
  "ludo_mech_min": null,
  "ludo_mech_max": null,
  "ludo_unit": "barg",
  "temp_min_hadoop": null
}

let result = {}
for (const [key, value] of Object.entries(obj)) {
  if (key.includes('_hadoop')) {
    result[key] = value
  }
}
console.log(result)

答案 1 :(得分:1)

您可以参考以下问题: JavaScript: filter() for Objects

您的Q将为:

   const obj = {
      "pi_diagram": null,
      "painting": null,
      "heat_treatment": null,
      "welding_procedure": null,
      "inspection_test": null,
      "pipecl_hadoop": null,
      "pipecl": null,
      "ludo_min_hadoop": null,
      "ludo_min": 4,
      "ludo_normal_hadoop": null,
      "ludo_normal": 6,
      "ludo_max_hadoop": null,
      "ludo_max": null,
      "ludo_test": null,
      "ludo_mech_min": null,
      "ludo_mech_max": null,
      "ludo_unit": "barg",
      "temp_min_hadoop": null
    };
    const filteredByKey = Object.fromEntries(Object.entries(obj).filter(([key, value]) => key.includes('_hadoop')))

console.log(filteredByKey);

答案 2 :(得分:1)

如果您要严格检查名称ends_hadoop并且名称不包含_hadoop,则需要像regex一样使用/_hadoop$/.test(propName)。 / p>

使用Object.keys(obj)获取array中所有keys的{​​{1}},然后用obj进行过滤,这样它将返回键/_hadoop$/.test(x)的数组与ends

然后使用_hadoop来构建新对象。

检查以下结果。

reduce