首页 > 解决方案 > 一种扁平化对象的优雅方式

问题描述

我正面临一个简单的问题,即用嵌套的对象来展平简单的对象。

尝试了 SO 的解决方案,但它会引发错误:

const newWeather = Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}({id: 1}))

// also tried these ones:

    console.log(Object.keys(weatherDetails).reduce((a, b, c) => {
        return Object.assign(a, {
            a: b
        })
    }, {})); 

// another one

let newWeather = Object.assign({}, (function() {
        var obj = {}
        for (var i = 0; i < Object.keys(weatherDetails).length; i++) {
            console.log(i, Object.keys(weatherDetails))
            obj[Object.keys(weatherDetails)] = weatherDetails[Object.keys(weatherDetails)]
        }
        return obj
    })())

这是我需要展平的对象,因此我们需要将其转为:

{ 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3
    }
}

进入这个:

{ 
    temperature: null, 
    humidity: null, 
    pressure: null, 
    windspeed: null, 
    PM1: 1,
    PM10: 2,
    PM25: 3
}

标签: javascriptarraysobjectreducehigher-order-functions

解决方案


假设您想要一个通用解决方案,而不是pollution使用静态键为您的示例量身定制的解决方案,这是实现该目标的一种快速方法:

您只需遍历对象的属性键。如果属性是对象(我们称其为子对象),您将把子对象的属性复制到主对象。

const obj = {
    temperature: null,
    humidity: null,
    pressure: null,
    windspeed: null,
    pollution: {
        PM1: 1,
        PM10: 2,
        PM25: 3
    }
};

function flatten(object) {
    for (const key in object) {
        if (!object.hasOwnProperty(key)) {
            continue;
        }

        if (typeof object[key] === 'object' && !Array.isArray(object[key]) && object[key] != null) {
            const childObject = object[key];
            delete object[key];
            object = {...object, ...childObject};
        }
    }
    return object;
}

console.log(flatten(obj));


推荐阅读