首页 > 解决方案 > 动态遍历一个 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)"
       },
   ]
},

我就是想不通,一定是星期一的雾!

谢谢

标签: javascriptarraysjson

解决方案


你可以用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);


推荐阅读