Rearrange the arrangement of the array of objects

I am working with an array of objects that looks like this:

[{
  "Germany": "text",
  "Brazil": "50.00"
}, {
  "Germany": "1000.00",
  "Brazil": "1100.00"
}, {
  "Germany": "999999999",
  "Brazil": "9999999",
  "France": "12"
}]

My goal is to transform it into the following structure:

[{
  "name": "Germany",
  "value": 999999999
}, {
  "name": "Brazil",
  "value": 999999999
}, {
  "name": "France",
  "value": 12
}]

In this new structure, for each key in the first object, I want to use the higher value among all the objects.

Note: If a value is text (e.g.,

"Germany": "text"
), it should be ignored. This case has been added in the example above.

Answer №1

If you want to achieve your desired result, one way is to utilize the `reduce` function. Within the reduce function, you can access the `Object.entries` of the current object to group by the country name.

const data = [{
  "Germany": "100.00",
  "Brazil": "50.00"
}, {
  "Germany": "1000.00",
  "Brazil": "1100.00"
}, {
  "Germany": "999999999",
  "Brazil": "9999999",
  "France": "12"
}];

const finalResult = Object.values(data.reduce((accumulator, currentValue) => {
    Object.entries(currentValue).forEach(([country, amount]) => {
        accumulator[country] ??= {country, total: 0};
        accumulator[country].total = accumulator[country].total > amount ? accumulator[country].total : amount;
    });
    return accumulator;
}, {}));

console.log(finalResult);

Answer №2

To loop through the objects, you can utilize .reduce and to iterate over each object entry, use .forEach:

const data = [
  { "Germany": "100.00", "Brazil": "50.00" }, 
  { "Germany": "1000.00", "Brazil": "1100.00" }, 
  { "Germany": "text", "Brazil": "9999999", "France": "12" }
];

const result = Object.values(data.reduce((accumulator,item) => {
  Object.entries(item).forEach(([name,value]) => {
    if(!isNaN(value)) {
      const previousValue = accumulator[name];
      if(!previousValue) accumulator[name] = { name,value } ;
      else if(previousValue.value < value) previousValue.value = value;
    }
  });
  return accumulator;
}, {}));

console.log(result);

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

Building a loading spinner component in a react-native project

I have successfully implemented a loading spinner that is currently being used in various components of my React project. However, as I am now working on a react-native version of the application, I am faced with the challenge of recreating this loading sp ...

Is the JavaScript file not being stored in the cache?

As I work on optimizing my web application, I am facing a challenge with a javascript file size of approximately 450K even after compressing it. While I intend to redo the javascripting in due time, for now, I need to go live with what I have. Initially, I ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

Exploring the complexities of object scope in Javascript

I'm having trouble accessing certain variables from a function. Here's the issue I'm facing: var PTP = function (properties) { this.errorsArray = [] } PTP.prototype.initHTMLItems = function () { $('input[data-widget-type="dat ...

Utilizing mongoose data for rendering in express

Currently utilizing the Hackathon-starter framework, I am looking to incorporate the user's name from the database into the render title property in express.js. The specific file that requires modification can be found here ...

React application not functioning on localhost:3000 despite successful compilation with no errors, only displaying the title on localhost but failing to show any content

I recently started developing a new website with React. Everything was running smoothly on localhost until I made some changes, and now the homepage content is not displaying when I visit localhost:3000. I suspect there may be an issue with my routing or s ...

Using a regular expression to match a JSON-formatted text file

I want to use regular expressions to match JSON formatted text in a file. I have attempted the following: data = [] location = '.' print(line) The data is stored in a text file (abc.txt). There are 10 files similar to th ...

Tips on sending a function's return value to an object in Node.js

I'm currently exploring Node.js and working on a REST API for a project. One of the functionalities I am implementing is a post request to store form data in a database. Some values will be retrieved from the form data while others will be generated ...

What is the best way to access the second array in a JSON object?

I have successfully implemented autocomplete with JSON and PHP. It is working fine, but now I am facing a challenge in retrieving the second array from the JSON data. Below is the script I have used in source.php: <?php $req = "SELECT namaBarang, har ...

How to create a sequence of queries to a mongoDB database (using mongoose) depending on a condition

Source Code let placeForSearch="hampi" let filteredHotelFacilities=req.body.filter //["Free Wifi"] let hotels = await Hotel.find({placeForSearch}) .where("facilities") .select(selectedProperties) .skip(pageNu ...

Retrieve the appended element's object

I am currently facing an issue with accessing elements that are automatically added by a library in my code. In my HTML, I have the following line: <div class="bonds" id="original" style="display:block;"></div> The library appends some elemen ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

Selenium's click() method in Python seems to experience issues when used within a script, but functions properly when used through

While working with python 3 selenium, I encountered an issue when trying to login to the Zomato website. When running a script, the login button was clicked but the dialog box did not open. However, when executing the same statements in the command line or ...

Is it feasible to solely utilize the "else" block for an "if...else" statement in JavaScript?

Is it possible to have an "else" block without an "if" statement in JavaScript? If so, what is the syntax for this situation? if (req.body[data].length <= maxlength[indx]); // <===== semicolon else { req.body[data] = 'ERROR: too lo ...

What other choices are available for the Angular ui-select2 directive?

Within the Angular select2 controller below: <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject"> @*ng-options="project.WebsiteName for project in projectList"*@ ...

What is the process of extracting "error" or "success" from JSON data using Kotlin?

While working on developing a web android app using Kotlin, I have been learning something new every day. However, there is one error that I have not been able to find a solution for. I am using OkHTTP3 and Klaxon for handling JSON data. My main requiremen ...

Leveraging Async/Await to track error counts across three distinct loops, each invoking an asynchronous function in every iteration

While I have experience with Callbacks, Async/Await and Promises are new concepts to me. In my node.JS server project, I am faced with the challenge of counting errors generated by thousands of asynchronous calls from three different async functions. My g ...

What is the process for choosing a table column by clicking on the "select" option?

Welcome to my project! Here is an example table that I'm working on. I have a question - how can I make it so that when I click on "choose me", the entire column is selected? Can you help me with this? <table> <tr> <th>plan A&l ...

Tips for including a subquery in query results using axis

I have a query for the objects table using an id. Then, I want to query the same table with the id from my result and add it as a new property. Does that explanation make sense? app.get(`/details`, (req, res) => { const { id } = req.query; connectio ...

What is the best way to transfer form input data from a child component to the parent component in React?

Recently delving into the world of React, I decided to experiment with forms. My project idea was straightforward - create a form component with input fields that, upon clicking submit, would pass the input values to the parent component ('App') ...