0
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

}

I am having this object , how to extract key value pair having '_hadoop' appended in key ??

njain
  • 147
  • 3
  • 7

3 Answers3

3

you can refer this Q : JavaScript: filter() for Objects

for your Q it would be as :

   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);
KcH
  • 3,302
  • 3
  • 21
  • 46
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)
holydragon
  • 6,158
  • 6
  • 39
  • 62
1

If you want to strictly check name ends with _hadoop and name doesn't contains _hadoop then you need to use regex like /_hadoop$/.test(propName).

Use Object.keys(obj) to get array of all keys of obj and then filter with /_hadoop$/.test(x) so it will return array of key ends with _hadoop.

Then use reduce to build your new object.

Check the result below.

const obj = {
  "pi_hadoop_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 = Object.keys(obj)
  .filter(x => /_hadoop$/.test(x))
  .reduce((a, x) => (a[x] = obj[x], a), {});

console.log(result);
Karan
  • 12,059
  • 3
  • 24
  • 40