这个问题通常出现在迭代嵌套的数据结构时,如对象中的数组或嵌套对象。要解决这个问题,我们可以手动实现递归地迭代和解构。以下是一个解决方案的示例,用于迭代嵌套对象并将其转换为具有扁平结构的数组:
const flattenObject = (obj) => {
const flattened = {};
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object' && obj[key] !== null) {
const nested = flattenObject(obj[key]);
Object.keys(nested).forEach(nestedKey => {
flattened[${key}.${nestedKey}
] = nested[nestedKey];
});
} else {
flattened[key] = obj[key];
}
});
return flattened;
};
// Example Usage: const nestedObj = { name: 'John', address: { street: '123 Main St.', city: 'Anytown', state: 'CA', zip: 12345 } }; const flattened = flattenObject(nestedObj); console.log(flattened); // Output: {name: 'John', 'address.street': '123 Main St.', 'address.city': 'Anytown', 'address.state': 'CA', 'address.zip': 12345}