首页 > 解决方案 > 基于 foreach 循环索引的动态数组名称 forEach((key) => { const temp[{ key }] }

问题描述


我正在尝试格式化从 JSON 对象获得的一些数据。
该对象有一个视频源:video.videodata
和视频转码的分辨率:video.transcoded

数据:
"video": [
  {
    "videodata": "https://example.com/link/to/firstTestvideo.mp4",
    "transcoded": [
      "-360",
      "-480"
    ]
  },
  {
    "videodata": "https://example.com/link/to/firstTestvideo.mp4",
    "transcoded": [
      "-360",
      "-480",
      "-720"
    ]
   }
],

我想将数据格式化为:

videos: [ //global
  video: [
    0: [ 
        {
         src: "https://example.com/link/to/firstTestvideo-360.mp4",
         resolution: "-360p",
        },
        {
         src: "https://example.com/link/to/firstTestvideo-480.mp4",
         resolution: "-480p",
        },
        {
         src: "https://example.com/link/to/firstTestvideo.mp4",
         resolution: "full",
        },
    ],
    1: [
        {
         src: "https://example.com/link/to/secondTestvideo-360.mp4",
         resolution: "-360p",
        },
        {
         src: "https://example.com/link/to/secondTestvideo-480.mp4",
         resolution: "-480p",
        },
        {
         src: "https://example.com/link/to/secondTestvideo-720.mp4",
         resolution: "-720",
        },
        {
         src: "https://example.com/link/to/secondTestvideo.mp4",
         resolution: "full",
        },
    ],
  ],
],

到目前为止,我得到了:

...
const filler = ajax.response;
Object.keys(filler.video).forEach((k) => {
  const temp = [];
  temp[{ k }] = []; // <-THIS DOES NOT WORK??
  this.videos[{ k }] = []; // this.videos is a global [].
  const item = filler.video[k];
  const sl = item.videodata.substring(0, item.videodata.length - 4);
  Object.keys(filler.acf.video[k].transcoded).forEach((x) => {
    temp[{ k }].push(
      {
        src: `${sl}${filler.video[k].transcoded[x]}.mp4`,
        resolution: filler.video[k].transcoded[x], 
      },
    );
  });
  Object.entries(temp).forEach((o) => { 
    this.videos[{ k }].push(o[1]);
  });
  });
});

任何想法如何创建视频的“子阵列”?
由于视频的数量是动态的,我不能做视频[0]、视频[1]等。

有没有更好的方法来格式化数据然后字符串连接?
不幸的是,我无法更改称为 JSON 的布局

任何想法都非常感谢!

标签: javascriptarraysjsonjavascript-objects

解决方案


只需检查这个小提琴并更改它:

 const fnl = []
    vidoes.forEach(index => fnl.push( ...index.transcoded.map(vd => ({
    src: index.videodata,
  resolution: vd + 'p'
    })))

js小提琴示例


推荐阅读