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

Issue encountered when trying to render Vue.js file with the view instance "new Vue()"

When working with vue.js and rendering a vue page, I encountered the following error: Error "Cannot GET /KForm" My code in main.js is as follows: import * as componentBase from "@app/app_start" import Form from "@views/Form/Form.vue" import KForm from ...

Creating a custom directive in AngularJS that utilizes an event listener

I am currently working on designing a custom directive that includes a text box. When a user clicks a button, the text box should expand and become focused. If the user then clicks away from the expanded text box, it should minimize, disappear, and display ...

Error message: The function client.on is not defined as a valid function

const Discord = require("discord.js"); const client = new Discord.Client(); module.exports = { name: "voiceStateUpdate", run: async (message, client) => { client.on("voiceStateUpdate", (o ...

Encountering the "EHOSTUNREACH" error message while attempting to establish a connection to an API through the combination of Axios and Express

Exploring the capabilities of the Philips Hue Bridge API, I delved into sending requests using Postman. To my delight, I successfully authenticated myself, created a user, and managed to toggle lights on and off. Verdict: Accessing the API is achievable. ...

The Vue multiselect component is unable to retrieve nested properties from a label

I am currently working with a data structure that looks like this: Proxy(Array) { 0: { id: 1, machineries_ID: 2, machinery: { id: 2, en_name: 'Digital MRI', pa_name: 'ډیجیټل ام ار ای', model_no: '2022', company_i ...

Is there a way to duplicate an image a specified number of times depending on a given output value?

As a beginner in coding, I am looking to learn how to dynamically insert multiple images based on input and output values. Currently, my code for basic addition looks like this: <form oninput="x.value=parseInt(a.value)+parseInt(b.value)"> <inpu ...

Building a Vue application with Node.js, Express, and XAMPP requires careful consideration of the project

I'm looking to develop a CRUD application using technologies such as: - Vue.js - Node & Express - mysqli (xampp) What would be the most effective approach to structuring the project's directory and files tree? Is it preferable to separate into t ...

Utilizing jQuery in your webpack configuration for optimal performance

I encountered some issues while trying to test a simple project that involves using a jQuery function with webpack. The errors occurred during the bundling process and are as follows: ERROR in ./~/jQuery/lib/node-jquery.js Module not found: Error: Cannot ...

I'd like to be able to click on the navbar and have the text color change using tailwind CSS

Click on the button to change its color. Click on another button to change its color as well, but the first button will revert back to its default color. View image description here <ul class="flex flex-col p-4 mt-4 border borde ...

PHP Array Parameter for Oracle Stored Procedures

I'm trying to call an Oracle Stored procedure that requires an array as an input parameter (Owa.vc_arr(varchar2)). When I make the call in PHP, I encounter an error. Any assistance with this issue would be greatly appreciated. The code I am currently ...

Pattern for Ajax callback in Javascript

I'm facing an issue with the code snippet below. var bar = { ajaxcall : function(){ var _obj = {}; $.ajax({ headers: { 'Content-Type': "application/json; charset=utf-8", 'da ...

Exploring the "else if" Statements in a JavaScript Calculator

I need help with modifying a calculator created by a former colleague at my workplace. Unfortunately, I haven't been able to contact them and I was hoping someone here could assist me. My knowledge of javascript is limited, so please bear with me if m ...

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

Is it possible to include a JavaScript script in a Laravel Blade file?

I have an Auth module from nwidart/laravel-Module. I am trying to include a script file in the Modules\Auth\Resources\views\layouts\app.blade.php file, like this: <body> ...... ... <!-- Scripts --> <script s ...

Cyclic Character Array Buffer - C

I've encountered a issue while using a circular char * array as a buffer to transfer data from multiple mapping threads to a reducing thread. My problem arises when the array runs out of space, causing segmentation faults. How can I resolve this issue ...

Step-by-step guide on incorporating a climate clock widget into your Angular project

Is there a way to integrate the Climate Clock widget from into my Angular project? Upon adding the following code snippet: <script src="https://climateclock.world/widget-v2.js" async></script> <script src="https://climateclo ...

Tips for exchanging divs in a mobile view using CSS

Illustrated below are three separate images depicting the status of my divs in desktop view, mobile view, and what I am aiming for in mobile view. 1. Current Status of Divs in Desktop View: HTML <div id="wrapper"> <div id="left-nav">rece ...

The JavaScript code is not executing properly within the HTML document

I am trying to execute a function from my JavaScript file in my HTML page. Here is the code snippet: index.html <!DOCTYPE html> <html><body> <h2>Web1</h2> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jq ...

Is it possible to refresh a tree without having to reload the entire webpage?

I'm currently developing a web application utilizing zTree library. The tree structure is populated with data retrieved from a Golang backend server. Each leaf node in the tree should have custom icons that can change dynamically while the application ...

Building a TypeScript Rest API with efficient routing, controllers, and classes for seamless management

I have been working on transitioning a Node project to TypeScript using Express and CoreModel. In my original setup, the structure looked like this: to manage users accountRouter <- accountController <- User (Class) <- CoreModel (parent Class o ...