Steps to generate a fresh array from a given array of objects in JavaScript

Looking to transform an existing array into a new array of objects in Vue.js.

Here's the initial array :

import { ref } from 'vue';

const base_array = ref([
  {id: 1, name: Pill, timing: [morning, noon, evening, night]},
  {id: 2, name: Tablet, timing: [morning, evening]},
])

Desired output :

const modified_array = ref([
  {id: 1, name: Pill, timing: [morning]},
  {id: 2, name: Pill, timing: [noon]},
  {id: 3, name: Pill, timing: [evening]},
  {id: 4, name: Pill, timing: [night]},
  {id: 5, name: Tablet, timing: [morning]},
  {id: 6, name: Tablet, timing: [evening]},
])

I've attempted using forEach and looping through the array, but haven't found the right solution yet. Appreciate any help. Thank you!

Answer №1

To achieve the desired outcome, you can utilize the flatMap method in the following manner:

const originalData = ref([
      { id: 1, name: "Pill", timing: ["morning", "noon", "evening", "night"] },
      { id: 2, name: "Tablet", timing: ["morning", "evening"] },
    ]);

const updatedData  = ref(originalData.value.flatMap(item => item.timing.map(time => ({id: item.id, name: item.name, timing: [time]}))));

Answer №2

This piece of code is functioning properly

const updated_array = ref(
    original_array.value.flatMap(({timing, ...rest}) =>
        timing.map(time => ({...rest, timing:[time]}))
    )
);

But, if you require updated_array to react to changes in original_array, it's better to use computed instead of ref just like shown below

If you observe, the output of modified_array changes when there is a change in base_array after three seconds using this script

setTimeout(() => original_array.value[1].timing.push('reactive!!!'), 3000);

In any case, here's an illustration of fully operational code for vue3

const { ref, createApp, computed } = Vue;


createApp({
    setup() {
        const original_array = ref([
          {id: 1, name: 'Pill', timing: ['morning', 'noon', 'evening', 'night']},
          {id: 2, name: 'Tablet', timing: ['morning', 'evening']},
        ]);
        const updated_array = computed(() =>
            original_array.value.flatMap(({ timing, ...rest }) =>
                timing.map((t) => ({ ...rest, timing: [t] }))
            )
        );
        setTimeout(() => original_array.value[1].timing.push('reactive!!!'), 3000);
        return { original_array, updated_array};
    }
    
}).mount('#app');
.as-console-wrapper { max-height: 0 !important; top: 0; }
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
  <ul>
    <li v-for="({id, name}) in original_array" :key="id">
    {{ id }}: {{ name }}
    </li>
  </ul>
  <ul>
    <li v-for="({id, name, timing}, i) in updated_array" :key="i">
    {{ id }}: {{ name }} {{timing[0]}} 
    </li>
  </ul>
</div>

Answer №3

If you want to achieve this, all you need to do is utilize the combination of Array.forEach() along with the Destructuring assignment.

Check out a Live Demo below:

const base_array = [
  {id: 1, name: 'Pill', timing: ['morning', 'noon', 'evening', 'night']},
  {id: 2, name: 'Tablet', timing: ['morning', 'evening']},
];

let modified_arr = [];
let index = 1;

base_array.forEach(obj => {
    const {id, name, timing} = obj;
  timing.forEach(t => {
    modified_arr.push({ id: index, name, timing: [t]})
    index++;
  })
});

console.log(modified_arr);

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

Utilizing a combination of MVC, jQuery, and Ajax to ensure that JavaScript is fully loaded before proceeding

Utilizing ASP.NET MVC and jQuery, I am loading a PartialView via Ajax which has its own accompanying JavaScript file. Upon successful retrieval of the html content, it is inserted into the DOM. However, there can be a delay between the insertion and the ex ...

The AJAX request is failing to reach the server

I'm currently using AJAX to populate a dropdown, but for some reason the call isn't reaching the server. Upon checking Firebug, I see the following error: POST 0 status 404 not found This is the code I'm working with: function selec ...

What steps should I take to develop an Outlook add-in that displays read receipts for action items in sent emails?

Currently, I am in the process of developing an add-in that will enable me to track email activity using a tool called lead-boxer (). With this add-in, I am able to retrieve detailed information about users who have opened my emails by sending them with an ...

JavaScript fails to function in an HTML file

I am facing an issue where my JavaScript code works perfectly in JSFiddle, but when I copy it into an HTML file, it doesn't function as expected. Despite searching through other related posts, I have been unable to find a solution for this specific pr ...

Having trouble with the Moment.js diff function in your React Native project?

Within my React Native application, I have implemented Moment.js and included the following code snippet: const expDate = moment(new Date(val)).format('MM-DD-YYYY'); const nowDate = moment().format('MM-DD-YYYY'); const diff = nowDate.d ...

Passing a callback function through a prop in Vue.js

Currently, I have a component structured in the following way: <template> <div> <pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination> </div> </t ...

Updating to a newer version of jQuery causes issues with pop-out submenus

Looking for a way to create a menu with pop-out submenus? Here's an example using jQuery: <script type="text/javascript"> $(document).ready(function() { var hoverAttributes = { speed: 10, delay: 1 ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

Dynamic font sizing in CSS allows text on a webpage to

I am working on creating a dynamic screen using AngularJS. Within this screen, there are objects with a specific size: .item { margin: auto; margin-bottom: 10px; width: 11vw; height: 11vw; text-overflow: ellipsis; overflow: hidden; } These i ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

Easily fetching data with AJAX through jQuery

Completely new to using jQuery and AJAX, I attempted the code below for a simple http get request: <html> <head> </head> <body> <script src = "jquery-2.1.4.js"></script> <script src = "app.js"></script& ...

Update the WooCommerce shopping cart page automatically upon product removal

After trying to solve the issue of refreshing the cart page in WooCommerce when a product is removed, I came across this helpful question on Stack Overflow: Refresh the page after product remove from cart Woocommerce. Following the provided code snippet th ...

jQuery UI Accordion - Adjusting Panel Height to Content Size

Currently, I am utilizing jQuery UI's Accordion feature from http://jqueryui.com/demos/accordion/, and my goal is to adjust it so that it resizes based on the contents of each panel rather than just fitting the largest one. In addition, I am seeking ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

React Jodit Editor experiencing focus loss with onchange event and useMemo functionality not functioning properly

I'm currently working on a component that includes a form with various inputs and a text editor, specifically Jodit. One issue I've encountered is that when there are changes in the Jodit editor's content, I need to retrieve the new HTML va ...

Tips for displaying an asp.net form using javascript functions

I am currently developing a login page in asp.net and have utilized a template from CodePen at http://codepen.io/andytran/pen/PwoQgO It is my understanding that an asp.net page can only have one form tag with runat="server". However, I need to incorporate ...

Challenges with incrementing in Jquery's each loop and setTimeout

http://jsfiddle.net/fxLcy/ - an example showcasing the use of setTimeout. http://jsfiddle.net/fxLcy/1/ - this demo does not include setTimeout. Although all elements are correctly positioned, I am in need of that delayed animation =/ My goal is to arrang ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Mastering SVG Path Coordinates using Pure JavaScript

Is it possible to target and manipulate just one of the coordinate numbers within an SVG path's 'd' attribute using JavaScript? For example, how can I access the number 0 in "L25 0" to increment it for animating the path? function NavHalf ...