[英]Partially flattening a JavaScript object
我有一个我无法修改的API接收到的JavaScript对象。 我想在工具中使用此数据,但是该工具仅接受存储在对象根级别的值,例如,我不能使用点表示法访问下一级的键值。
基于下面的示例,我希望能够访问shape.colour
,但是可以通过从新的JSON对象引用诸如shape__colour
东西来进行访问。
起始对象示例:
[{
"id" : 12345,
"size" : 40,
"shape": {
"colour" : 'yellow',
"dimension" : '2D'
}
},
{
"id" : 12346,
"size" : 50,
"shape": {
"colour" : 'blue',
"dimension" : '3D'
}
}]
我需要它看起来像什么:
[{
"id" : 12345,
"size" : 40,
"shape__colour": 'yellow',
"shape__dimension" : '2D;'
}
},
{
"id" : 12346,
"size" : 50,
"shape__colour": 'blue',
"shape__dimension" : '3D'
}
}]
我遇到的其他对象平展函数的示例似乎产生了一个单层数组(完全删除了对象),而我需要保留单个对象,但要将其中的数据放在一个级别上。
任何帮助将不胜感激!
另一个map
功能:
const result = arr.map(
({shape, ...rest}) => ({ shape__colour: shape.colour, shape__dimension: shape.dimension, ...rest })
);
或者形状具有动态属性:
const result = arr.map(
({shape, ...rest}) => Object.assign(rest, ...Object.keys(shape).map(key => {["shape__"+key] : shape[key]}))
);
您可以使用map
返回具有flated shape属性的新数组:
let result = arr.map(({id, size, shape}) => {
return {
id,
size,
shape_colour: shape.colour,
shape_dimension: shape.dimension
}
});
注意:您也可以在参数列表中解构形状对象:
let result = arr.map(({
id,
size,
shape: { colour: shape_colour, dimension: shape_dimension }
}) => {
return {
id,
size,
shape_colour,
shape_dimension,
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.