Creating an array of dynamic variable names based on the index of a foreach loop, where each variable is assigned the value of `temp` at the corresponding


Trying to organize data extracted from a JSON object.
The object contains a videosource: video.videodata
and the various transcoded resolutions: video.transcoded

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

Desired format:

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",
        },
    ],
  ],
],

Current approach:

...
const filler = ajax.response;
Object.keys(filler.video).forEach((k) => {
  const temp = [];
  temp[{ k }] = []; // <-NOT WORKING??
  this.videos[{ k }] = []; // 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]);
  });
  });
});

Looking for suggestions on creating "Subarrays" of videos.
Due to the changing number of videos, static indexes like video[0], video[1], etc. won't work.

Any alternative ways to format the data without string concatenation?
Unfortunately, modifying the JSON layout is not an option.
 
Appreciate any ideas!

Answer №1

Take a look at this fiddle and make the necessary modifications:

 const finalList = []
    videos.forEach(i => finalList.push( ...i.transcoded.map(v => ({
    src: i.videoData,
  resolution: v + 'p'
    })))

Check out the js fiddle demo

Answer №2

The explicit 0:, 1: elements appear to offer no added value, so this script simplifies the process using a basic array structure. The intended functionality of accessing videos.video[0][0] can be achieved through this method, as demonstrated below:

const data = {
  "video": [{
      "videodata": "https://example.com/link/to/firstTestvideo.mp4",
      "transcoded": [
        "-360",
        "-480"
      ]
    },
    {
      "videodata": "https://example.com/link/to/firstTestvideo.mp4",
      "transcoded": [
        "-360",
        "-480",
        "-720"
      ]
    }
  ]
};

const videos = {
  video: data.video.map(item => [...item.transcoded, "full"].map(resolution => ({
    src: item.videodata,
    resolution
  }))
};
console.log("videos:");
console.log(videos);
console.log("---");
console.log("videos.video[0][0]:");
console.log(videos.video[0][0]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2: Refine array based on a condition

I need to filter data in an object array based on a predicate. The tricky part is constructing the predicate, which should be similar to building a query using a Map data structure. Here is an example of my objects array: var data = [ {"id": 1, "name" ...

The selected option is not visually highlighted in the ui-select due to a programming issue

angular version: AngularJS v1.3.6 http://github.com/angular-ui/ui-select : Version: 0.8.3 var p1 = { name: 'Ramesh', email: '[email protected]', age: 99 }; $scope.people = [ { name: 'Amalie', ...

In Python, transforming a bytearray into a ctypes Struct

I have a bytearray with a size of 'n'. This array is structured similarly to one of the defined ctypes.Structure objects. I am looking to convert this bytearray into that structure so that I can access each individual member. What steps should I ...

Trouble with Boostrap popover functionality when injecting HTML into the code

I am facing a challenge in creating dynamic popovers that are triggered by a 'dictionary' array to insert HTML content into existing text on the webpage. Initially, the code was meant for tooltips and worked flawlessly. However, I am now attempti ...

I attempted to include multiple images in my HTML using Vue.js, but encountered an error message stating "illegal invocation"

Here is my HTML code: <form method="POST" v-on:submit.prevent="handleSubmit($event);"> <div class="row"> <div class="col-md-4"> <div class="form-group label-floating"> <label class="control-label">Name</label> <input ...

Dilemma when encoding a MySQL query with accents into a JSON object using PHP

Whenever I attempt to encode a query from a MySQL database into JSON, I encounter an issue where the output is null when the words contain accents such as "olá", "à", etc. Here is my PHP code: $sql = "SELECT `name` FROM `login` WHERE ...

What is the most effective way to prevent actions while waiting for ajax in each specific method?

Within my JS component, I have various methods that handle events like click events and trigger ajax requests. To prevent the scenario where multiple clicks on the same button result in several ajax requests being fired off simultaneously, I typically use ...

Navigating intricate data structures within React

As a newcomer to React, I could use some assistance with a project I am working on. The application is similar to Slack, where users can create new teams and channels. However, I am encountering difficulties in managing the state of the data input throug ...

Modify the JSON structure of a deeply nested object

I am attempting to convert a deeply nested JSON object from one structure to another so that it can be properly used with the jQuery Nestable library. Here is the original format I am working with: { "scanned": { "a3": { ...

Is there a way to exclude specific elements from the object before returning it, instead of returning the entire object?

When the user object is returned, certain fields like password, confirmationToken, and __v are hidden. Here is an example of the user object before filtering: { "user": { "_id": "566786", "detail": { "lastUpdate": "2015-01- ...

Difficulty displaying API information on a web browser with react.js

I am currently working on developing a trivia game using React.js Typescript and The Trivia API. I have been successfully passing data between components with useContext and navigating through components using react-router-dom. However, I encountered an is ...

"Sorry, cannot make a request for the relation field at

I am encountering difficulties when attempting to retrieve the relation field from the API. export async function fetchContent(params) { const reqOptions = { headers: { Authorization: `Bearer ${process.env.API_TOKEN}` } ...

Is the object returned by the useParams hook maintained across renders?

The book that is displayed is based on the URL parameter obtained from the useParams hook. The selected book remains constant across renders unless there is a change in the value returned by the useParams hook. I am curious to find out if the object retur ...

How can I direct to an HTML file using Vue 3 router?

I'm working with Vue 3 and I have a unique challenge. I want to connect a static landing page HTML file to the home route / in my Vue application, but this HTML file is completely separate from the original index.html used by Vue 3. This standalone HT ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

Guide to rendering the chosen option of an input dynamically in EJS

I have a dropdown menu where users can select an option to send to the database. Now, when they revisit the page, I want them to see the option they previously selected. Using EJS templating: <div class="form-group col-sm-6" style="width: 50%;"> ...

Access a three.js scene from a canvas element within the local environment to make alterations

Is it necessary to keep Three.js variables (scene, camera, renderer etc.) globally? I have devised a function that initializes canvas elements by taking a DOM position and other information to build the scene. This function is then passed to a render func ...

Encountering the java.lang.NoClassDefFoundError error is a common issue that arises specifically in

Currently, I am successfully using protobufs with the play framework 2.1.3. However, I encountered a need to convert the protobufs to JSON, which prompted me to include "com.googlecode.protobuf-java-format" % "protobuf-java-format" % "1.2" in Build.scala ...

Building a local database using the MVC framework concept

Can a locally stored database be developed using MVC framework principles in javascript and html5? Thank you Ravindran ...

Vue.js: Utilizing async/await in Vue.js results in an observer being returned

Currently, I'm attempting to retrieve data from an API and store it in an array. The issue arises when I try to log the response data from the API - the data is displayed just fine. I assign the value of a variable to the data obtained from awaiting t ...