遍历一个对象返回一个数组数组里面包含对象中的指定key值
function getObjectValues(obj, key) { const result = [];
for (const prop in obj) { if (obj.hasOwnProperty(prop) && prop === key) { result.push(obj[prop]); } else if (typeof obj[prop] === 'object') { result.push(...getObjectValues(obj[prop], key)); } }
return result; }
// Example usage: const myObj = { foo: 'bar', baz: { hello: 'world' }, qux: { fizz: 'buzz' } };
const values = getObjectValues(myObj, 'hello'); // returns ['world']
console.log(values);
原文地址: https://www.cveoy.top/t/topic/baqP 著作权归作者所有。请勿转载和采集!