我面临着用嵌套对象压平简单对象的琐碎问题。
尝试了 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
}
最佳答案
假设您想要一个通用的解决方案,而不是使用静态键为您的 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));
关于javascript - 一种扁平化对象的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56904319/