Tips for rearranging object properties within an array of objects

In my coding project, I am working with an array of objects structured like this:

currentArray = [
  {
    year: 2011,
    asset: {
      silver: 322,
      gold: 325,
    },
  },
  {
    year: 2012,
    asset: {
      silver: 411,
      gold: 2235,
    },
  },
];

I need to transform this current structure into a new format in JavaScript/TypeScript. Specifically, I want the 'silver' and 'gold' properties from each 'asset' object to be moved up one level next to the 'year'. Additionally, I need to remove the nested 'asset' objects entirely. The desired structure should look like this:

desiredArray = [
  {
    year: 2011,
    silver: 322,
    gold: 325,
  },
  {
    year: 2012,
    silver: 411,
    gold: 2235,
  },
];

Answer №1

const newArray = [{
    year: 2013,
    asset: {
      silver: 522,
      gold: 625,
    },
  },
  {
    year: 2014,
    asset: {
      silver: 712,
      gold: 3235,
    },
  },
];

newArray.map(element => {
  Object.assign(element, element.asset)
  delete element.asset;
  
  return element
})

console.log(newArray)

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

Transform JavaScript variables into CSS variables

Similar Post: Avoiding repeated constants in CSS I am currently working on a javascript file that aims to adjust my site's resolution based on the width and height of the viewport. While I have successfully retrieved these values using JavaScript ...

What steps can I take to troubleshoot and fix the height of a div/span element?

Here is my HTML code: <div> <span style="display: inline-block;height:20px">20</span> <span style="display: inline-block;"><img src="img/ex.png"/></span> </div> The image I have in the second span is sized at ...

What causes the JavaScript function to have an undefined return value?

I have written a function that is designed to determine the size of an image and return an object containing both the width and height. However, I am encountering an issue where the values for sz.width and sz.height are defined within the function but beco ...

Escaping backslashes in Unicode with Javascript

Similar Question: How do I decode a string with escaped unicode? I have a JavaScript variable that contains a Unicode character. var value = "\\u53d3\\u5f13\\"; When I add the above value dynamically to a div, the prope ...

"Adding a .js file to your Google App Engine project: a step-by-step guide

When working on my app, I encountered an issue with including a separate .js file in my .jsp frontend page. This is how my directories are arranged: src |--->com.stuff |--->servlet.java war |-->WEB-INF |--->pages |---->pa ...

Utilizing CodeIgniter to Transfer an Array seamlessly Through Model, Controller, and View

When my model in CodeIgniter sends an error response to the controller, which is then passed to a view encoded as JSON, I face a specific issue. The array returned from the model looks like this: return $posts[] = array('complete'=>0,'er ...

AngularJS array modification log tracker

In my current situation, I want to bind a list of objects to an HTML table using AngularJS's two-way data binding. It's a straightforward scenario without anything too complex. I have a couple of questions: When monitoring changes in the mod ...

Resolve object malfunction in Mozilla browser

Hey there! I recently developed a JavaScript Library known as Tocl. It has been running smoothly on Chrome and Safari, but unfortunately, I'm facing some issues when testing it on Mozilla browsers (Firefox, Aurora). The console is showing errors like ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...

The accuracy of the resulting data cannot always be guaranteed after the completion of each function execution. Calculate the function once

Using promises isn't exactly the same in this scenario - as the result depends on multiple service calls being made to populate an array of car makes. <td ng-show="IsOK(obj)" class="text-center"> <img ng-show="GetStatus(obj)=='&apos ...

Executing the stop button in the browser with Webdriver IO

Just a bit of background: The program I'm testing is located within another website that requires login credentials. Once logged in, I can access the screen I need to test by typing in the direct link. However, there's an issue where my automated ...

knockout.js' $root leads to a page displaying nothing

Using the $root binding context is resulting in a blank page for me. Removing it allows the page to load properly. Causing blank page: <td><input data-bind="value: name" /></td> <td><select data-bind="options: $root.availableMe ...

How can I link JSON array data to a chart.js using the same canvas ID?

Here is the HTML Canvas code: <div> <canvas id="chartdiv" width="200" height="200"></canvas> </div> Below is the JSON data: [{ "SID": "1", "NAME": "niten", "FTEPERCENT": "71.29", "FTCPERCENT": "28.71" }, { ...

In Next.js, the 404 error page is displayed using getInitialProps

Currently, I am learning how to redirect users in getInitialProps by following a helpful example. Here is the link to the example I am referring to However, I encountered an issue where when I try to return a 404 error using the code snippet provided, in ...

What is the best way to combine arrays using numpy for a mosaic effect

I am facing a challenge with reassembling a numpy array of shape (780,256,256) which represents 780 tiles of an image into the original image. I am struggling to properly reshape it. The goal is to arrange the 780 tiles in a grid layout of 26x30, resultin ...

Mongoose parameters do not accept passing an id or element

When working with MongoDB and using mongoose, I attempted to remove an item from a collection by utilizing the findByIdAndDelete() method. However, I encountered the following error: CastError: Cast to ObjectId failed for value "5f080dd69af4c61774ef447f" a ...

What is the current most stable and widely installed version of Angular 12?

Can anyone recommend an angular 12 version that is known for being extremely stable, having minimal bugs, and also compatible with angular fire ^6.1.5? I appreciate any input! ...

Tips for including a sequelize getter in a model instance?

I'm currently struggling to add a getter to the name field of the Company model object in my project. Despite trying various approaches, I haven't had any success so far. Unfortunately, I also couldn't find a suitable example to guide me thr ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

How come when I click on the edit button, the selected data's model doesn't appear in the dropdown menu as I would like it to?

this is the function in my controller public function getModel($make_id = null) { $make_id = request()->make_id; $carsmodel = CarModel::where('make_id', $make_id)->orderBy('model', 'ASC')->get(); return re ...