部分展平JavaScript对象 [英] Partially flattening a JavaScript object

查看:33
本文介绍了部分展平JavaScript对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我无法修改的API接收到的JavaScript对象.我想在工具中使用此数据,但是该工具仅接受存储在对象根级别的值,例如我不能使用点表示法向下访问键的值.

I have a JavaScript object that I receive from an API that I cannot modify. I would like to use this data within a tool, but the tool only accepts values stored on the root level of the object e.g. I cannot use dot notation to access the value of a key a level down.

基于下面的示例,我希望能够访问 shape.colour ,但是可以通过新的JSON对象引用 shape__colour 之类的东西.

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.

示例起始对象:

[{
  "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.

任何帮助将不胜感激!

推荐答案

另一个 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]}))
);

这篇关于部分展平JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆