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

Error: The prop type validation failed because a `value` prop was provided to a form field in React-Bootstrap-Typehead component

I am currently using the bootstrap-typehead package from https://github.com/ericgio/react-bootstrap-typeahead and struggling to understand why it's causing issues. Could someone help me identify what's wrong with this code that's triggering ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

Error encountered while parsing a file: JSON parsing failed due to an unexpected token 'g' at position

https.get('example.com/phpfilethatechoesandimtryingtograbtheecho.php', (res) => { console.log('statusCode:', res.statusCode); onsole.log('headers:', res.headers); res.on('data', (d) => { return ...

Implementing universal design in Next.js 14

I'm encountering a problem while trying to use the style jsx global property in the latest version of Next.js. Previously, you would include it in the _app.js file, but since that file no longer exists, I assumed it should be added to the layout.tsx f ...

What is the process for importing JSON from an NPM package in Angular version 15?

I've been dealing with a local package that contains a json file, and my current challenge is to load this json file into the Angular 15 app.component.ts. To bring the json file package into my Angular project, I followed this installation process: n ...

What is the best way to get jsDoc "import" to function properly in vscode?

Is it possible to import a node module using @import in Visual Studio Code? I'm trying it but it doesn't seem to be recognized. Am I missing something? https://i.stack.imgur.com/zq1rz.png ...

Continuously decrease a sequence of identical numbers in an array through recursion

One of the key challenges was to condense an array of numbers (with consecutive duplicates) by combining neighboring duplicates: const sumClones = (numbers) => { if (Array.isArray(numbers)) { return numbers.reduce((acc, elem, i, arr) => { if ( ...

What is the best way to refresh an Angular model containing nested data?

This week, I started working on a proof of concept with Angular Material where I have a table displaying nested data: <table> <thead> <tr> <th colspan="2">Employee Name</th> <th>Ovr&l ...

Ensure Safari sends the Origin header in jQuery GET requests

When I send a request from https://app.example.com, the following code is executed: $.get('https://api.example.com', { foo: 'bar' }) .success(getSuccess) .error(getError); This script runs smoothly on Chrome and Firefox, however, ...

What is the best way to retrieve declared functions within the done() scope of a jQuery plugin that handles JSON requests?

As I work on a jQuery plugin, my goal is to make it easily configurable and maintainable. To achieve this, I am focusing on keeping the functions short and testable. To accomplish this, I am implementing jQuery plugin code inspired by Addy Osmani's L ...

Unusual Methods in Vue.js: Exploring Odd Behavior

In my application, I have a single data variable called message, as well as a method in the methods section that performs cryptographic algorithms. Below is the code snippet: export default { data: () => ({ message: "" }), methods: { clic ...

Utilize a solo input field to upload either a video or image, and showcase a preview of the uploaded content in a

I'm currently working on creating an input field that allows for the upload of both images and videos. Although I am able to successfully upload the files, I'm encountering an error when trying to display a preview. The code snippet below outline ...

Utilizing margins in CSS for various div elements

Update: I have included Javascript and Masonry tags in my project. Despite having modules of the same size, I am exploring how masonry can assist me. However, I find it a bit puzzling at the moment as I am not aiming to align elements of different sizes. I ...

Excluding /build/ path from the URL in Laravel Vue 3

I am relatively new to Laravel and English is not my primary language, so please forgive any grammar mistakes. My project consists of a Laravel API with a Vue front-end. The Laravel web routing directs all traffic to a single blade file that contains the V ...

Using PHP as a data source, implement a feature in Google Maps that

I am currently working on incorporating an array of markers that are generated in PHP to a Google map. Below is the JavaScript code for my map: var map; var markers = []; var mapOptions = { //center: new google.maps.LatLng(locations[0].lat, locations[0 ...

What are some ways to streamline this D3 script?

My CSV data displays pass rates by organisation for different years: org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total GSK,industry,35,100,45,100,55,100 I am using D3 and aiming to create a dictionary of organisations struc ...

Spin an icon when the Button it is inside of is clicked

I am currently using a Material-UI button with the following code: <Button disableFocusRipple={true} disableRipple={true} color="inherit" onClick={openBlogMenu} className={classes.blogButtonStyle} > <LibraryBooksIcon /> Blog {! ...

Troubleshooting MongoDB and Node.js: Issue with updating variables when inserting documents in a loop

As a newcomer to MongoDB, I'm facing a puzzling issue that has left me confused. In my dataset, I have an array of Employee objects structured like this: { "Name" : "Jack Jackson", "Title" : "Senior Derp Engineer", "Specialties" : [ "Kicki ...

Encountering an error with an undefined property while trying to extract information from a JSON string

Here is the JSON string I have: { "data": [ { "id": "533513150124231", "created_time": "2015-02-27T05:23:02+0000", ... }, { "id": "533911933417686", "created_time": "2015-02-28T07:18:09+0000", ... }, { "id": "533471226795090", "created_tim ...

Executing ESM-Enabled Script in Forever

Is it possible to execute a script using the option -r esm in Forever? When I try to run the configuration below, I encounter an error message that reads: Unexpected token import. Here is the configuration: { "uid": "app", "script": "index.js", "s ...