[英]Partially flattening a JavaScript object
I have a JavaScript object that I receive from an API that I cannot modify. 我有一个我无法修改的API接收到的JavaScript对象。 I would like to use this data within a tool, but the tool only accepts values stored on the root level of the object eg I cannot use dot notation to access the value of a key a level down. 我想在工具中使用此数据,但是该工具仅接受存储在对象根级别的值,例如,我不能使用点表示法访问下一级的键值。
Based on the example below, I'd like to be able to access shape.colour
, but by referencing something like shape__colour
instead, from a new JSON object. 基于下面的示例,我希望能够访问shape.colour
,但是可以通过从新的JSON对象引用诸如shape__colour
东西来进行访问。
Example starting object: 起始对象示例:
[{
"id" : 12345,
"size" : 40,
"shape": {
"colour" : 'yellow',
"dimension" : '2D'
}
},
{
"id" : 12346,
"size" : 50,
"shape": {
"colour" : 'blue',
"dimension" : '3D'
}
}]
What I need it to look like: 我需要它看起来像什么:
[{
"id" : 12345,
"size" : 40,
"shape__colour": 'yellow',
"shape__dimension" : '2D;'
}
},
{
"id" : 12346,
"size" : 50,
"shape__colour": 'blue',
"shape__dimension" : '3D'
}
}]
Other examples of object flattening functions that I've come across seem to produce a single level array (removing the objects altogether), whereas I need to keep the individual objects, but for the data inside them to be on one level. 我遇到的其他对象平展函数的示例似乎产生了一个单层数组(完全删除了对象),而我需要保留单个对象,但要将其中的数据放在一个级别上。
Any help would be greatly appreciated! 任何帮助将不胜感激!
Another map
function: 另一个map
功能:
const result = arr.map(
({shape, ...rest}) => ({ shape__colour: shape.colour, shape__dimension: shape.dimension, ...rest })
);
Or if shape has dynamic properties: 或者形状具有动态属性:
const result = arr.map(
({shape, ...rest}) => Object.assign(rest, ...Object.keys(shape).map(key => {["shape__"+key] : shape[key]}))
);
You can use map
to return a new array with the flattened shape properties: 您可以使用map
返回具有flated shape属性的新数组:
let result = arr.map(({id, size, shape}) => {
return {
id,
size,
shape_colour: shape.colour,
shape_dimension: shape.dimension
}
});
Note: you can also destructure the shape object in the arguments list: 注意:您也可以在参数列表中解构形状对象:
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.