What is the method for inserting data into an array of objects in JavaScript?

I have a question regarding how to push/replace data into an object of an array of objects. Please excuse any mistakes in my grammar. Here is my dummy data:

const dummyData = {
      id: 1,
      daerah: "Bandung",
      date:"1668790800000",
      kendaraan: [
        {rodaEmpat: 50},
        {rodaDua: 22},
        {truck: 30},
        {Bus: 70},
      ]
    }, {
      id: 2,
      daerah: "Tasik",
      date:"1668877200000",
      kendaraan: [
        {rodaEmpat: 80},
        {rodaDua: 15},
        {truck: 10},
        {Bus: 50},
      ]
    },

Here is the variable 'data' that I want to push into:

 data: {
        
        datasets: [
          {
            data: [50, 40, 80, 19],
            backgroundColor: ["#6225E3", "#E32525", "#E7A543", "#3EAFE0"],
          },
        ],
      },

I want to push/override data.datasets[0].data with values from dummyData.kendaraan (this data needs to be processed using the map function first). The expected result should look like this:

data: {
        
        datasets: [
          {
            data: [50, 22, 30, 70],
            backgroundColor: ["#6225E3", "#E32525", "#E7A543", "#3EAFE0"],
          },
        ],
      },

Thank you for your help!

Answer №1

let vehiclesList = cars.map(car => Object.values(car)[0])
//vehiclesList = [50, 22, 30, 70]

The map method is a useful tool in this scenario.

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

Preserving classes in JQuery after making AJAX requests

Before we proceed, it's important to note that I am unable to modify any of the existing calls, code, or functions. This means I must come up with a workaround solution. So, here's the situation: I have a form containing various fields and a dro ...

How to use jQuery to hide list items after a certain threshold

$('li[data-number=4]').after().hide(); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li data-number="0"">1</li> <li data-number="1">2</li> ...

What is the best way to get process.argv to display only the arguments and exclude the node command and path?

As the title suggests, I am working on a substantial project that involves AppleScript and iMessage. After testing the script, it successfully opens Terminal and executes: node ~/Desktop/chatbot [argument]. However, at the moment, all it returns is: [ &apo ...

Ensure that newly added elements are aligned with the settings of the slide's

I've encountered an issue with my jQuery slider that affects a div's CSS on slide. Everything works as expected, except when I add a new div, the settings from the slider aren't applied to the new div until the slider is moved again. HTML ...

Is Vue JSON.parse throwing an error due to whitespace?

When I receive a json_encoded return value from PHP, it appears fine. However, when passing this value to my Vue application, the format gets distorted. Here's what's happening: {"data":{"format":"d\/m\/Y H:i:s"}} In my Vue applicatio ...

How can I load a specific div region using ajax for submitting a form?

I'm not sure if my approach is correct. On my main page, I have some information displayed. When you click a button, the form will load from a separate file: $('#viewport').load('/views/myView.php #targetDiv') This works fine ...

What is the best approach to create a dynamic value from axios response in a reactive object?

I am attempting to retrieve data from the backend (specifically the user role) and store it in a reactive container with Vue: import {reactive} from "vue"; import axios from "axios"; export const store = reactive({ auth: axios.get ...

Tips on sending data with a unique identifier to the backend through a route parameter

Can anyone help me figure out how to send a message to a specific backend route parameter while passing the current ID? I'm not sure how to inform the system about this ID. Here's the Vuex action: postMessage({commit}, payload, id) { axios.pos ...

Utilizing .html() to convert JSON data into HTML content

I have thoroughly commented the code below in my attempt to retrieve JSON data and pass it to the 'results' div in my HTML view. However, this process seems to return nothing, making it challenging to debug since no output can be displayed on the ...

Mastering the art of building a datepicker: A comprehensive guide

Looking for advice on how to create a datepicker in HTML without relying on bootstrap or pre-built JavaScript and CSS. I am interested in learning the process from the ground up and understanding how developers have designed these tools. I am specifically ...

Experimenting with Vue in conjunction with a web component

I am facing an issue with astrouxds web components in my application. During testing, I am receiving a warning that needs to be resolved. Additionally, I need help on how to properly assert a value in the web component. console.error node_modules/vue/dis ...

Instruct npm to search for the package.json within a designated directory

Imagine having a folder structure that looks like this: root |-build |-package.json |-src |-foo |-foo.csproj |-foo.cs |-bar.cs |-bin |-... |-foo.sln Now, if you change the current directory to root\src\foo\bin a ...

The isAuthenticated status of the consumer remains unchanged even after being modified by a function within the AuthContext

I am working on updating the signout button in my navigation bar based on the user's authentication status. I am utilizing React Context to manage the isAuthenticated value. The AuthProvider component is wrapped in both layout.tsx and page.tsx (root f ...

Enclosing values in JavaScript literals

I apologize for the inconvenience. I am unsure why it is not functioning properly. If I input <button type="button" onclick="document.getElementById("demo").innerHTML = Date()">click</button> the above code does not work. However, if I u ...

Steps for resolving the error message: "An appropriate loader is required to handle this file type, but there are no loaders currently configured to process it."

I am encountering an issue when working with next.js and trying to export a type in a file called index.ts within a third-party package. Module parse failed: Unexpected token (23:7) You may need an appropriate loader to handle this file type, current ...

Creating an image selection feature using ejs and express: a step-by-step guide

As I develop a blog site with a unique post management system using node, express, moongoDB, and EJS, everything seems to be running smoothly. However, the challenge arises when attempting to integrate Cloudinary uploaded images from my mongoDB to allow fo ...

Switching over to the latest version of Material-UI, v1.x.x

Currently, my app relies on Material-UI v0.17.0 which is not compatible with React v16.0.0. In order to make it work, I need to upgrade to Material-UI v1.0.0. I came across a migration tool here, but it only updates import statements. Many props have chan ...

Display the footer once the user has reached the end of the page by scrolling

Below is the footer code I am working with. <div class="row"> <div class="col-md-12"> <div> this section always remains at the bottom </div> </div> <div class="col-md-12"> <div> only v ...

Unspecified outcome of Ajax array as a choice in Select

I'm fairly new to working with AJAX / JSON and I'm having trouble figuring out how to parse an AJAX array response into a <select> dropdown. Despite going through several online tutorials and attempting different approaches to return the r ...

Passing down slots to child components in Vue allows for flexible and dynamic content

I am looking to create a reusable Data Table component using Vuetify. Some columns may require the use of v-slot to modify the data displayed within that specific column. For example, I have user roles stored as integers and want them to be shown as either ...