javascript - 动态遍历一个 json 数组并添加到另一个数组
问题描述
我有大量的 json 对象,我需要遍历它们并将它们添加到另一个 json 数组中。
该数组如下所示 -
{
id : 1,
name : "test1",
location : "London",
cost: "120.83"
},
{
id : 2,
name : "test2",
location : "shanghai",
cost: "124.83"
},
{
id : 3,
name : "test3",
location : "Barcelona",
cost: "56.54"
}
我使用的实际数组有 73 个键、值对和大约 20000 个对象。
我正在尝试将每个单独的对象转置到另一个数组中,这需要看起来像 -
{
cells:
[
{
value: 1,
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "test1",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "London",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "120.83",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
]
},
{
cells:
[
{
value: 2,
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "test2",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "shanghai",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
{
value: "124.83",
textAlign: "center",
background: "rgb(255,255,255)",
color: "rgb(0,62,117)"
},
]
},
我就是想不通,一定是星期一的雾!
谢谢
解决方案
你可以用Array.map()
and做到这一点Object.values()
:
const data = [
{ id : 1, name : "test1", location : "London", cost: "120.83" },
{ id : 2, name : "test2", location : "shanghai", cost: "124.83" },
{ id : 3, name : "test3", location : "Barcelona", cost: "56.54" }
];
const cell = { textAlign: 'center', background: 'rgb(255,255,255)', color: 'rgb(0,62,117)' };
const result = data.map(x =>
({ cells: Object.values(x).map(v => ({ value: `${v}`, ...cell })) })
);
console.log(result);
推荐阅读
- c# - 无法在 VS2017 上转换 T4 模板
- jboss - 来自 Wildfly 中部署的战争文件的 sun.applet.AppletSecurityException
- neo4j - Neo4J 3.4 `date` 函数是如何工作的?
- javascript - ES6 / JavaScript - 如何在特定键上合并对象
- amazon-s3 - 使用身份验证将数据从 S3 存储桶导入 Neo4j
- python - 对象检测 - 如何使用 CNN 检测和提取特征并使用分类器对其进行分类?
- python - 在 Windows 上与女服务员一起服务 Flask 应用程序
- javascript - 减去两次以给出 javascript 中的总分钟数(非标准时间格式)
- android - 在闪屏活动期间进入全屏
- python - 如何安全地将外键字段与 Django ModelForm 绑定