javascript - 一种扁平化对象的优雅方式
问题描述
我正面临一个简单的问题,即用嵌套的对象来展平简单的对象。
尝试了 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));
推荐阅读
- java - JSch 在终端上无休止的响应打印
- python - 是否有可能从 PyBind11 获取数组基础,而不仅仅是视图?
- java - 如何在图表中可视化具有多个级别的java复杂集合对象
- json - 使用 Json 将票证从 VBA 发送到 Jira
- javascript - 如何在不删除原件的情况下复制元素?
- python - 基于文本的游戏的循环中的函数
- azure - 子域下 Azure 上的网站部署
- java - Spring Cloud Gateway 错误:无法注册“tokenRelayGatewayFilterFactory”
- highcharts - 使用 Highcharts 时找不到 Json 文件
- excel - 使用时间戳保存时出现类型不匹配错误