Ways to combine all similar key values into an array

Apologies if the question seems unclear. Essentially, I am dealing with an object structured as follows:

[{"6":6.5},{"4":4.2},{"6":6.3}]

My goal is to eliminate duplicate keys while preserving their values, and merge them into a single unique key, forming an array like so:

[{"6":[6.5, 6.3]}, {"4": 4.2}]

Any suggestions on how to achieve this?

Answer №1

.reduce() is the perfect solution for your needs:

var data = [{"6":6.5},{"4":4.2},{"6":6.3}];

var res = data.reduce((rv, obj) => {
  var key = Object.keys(obj)[0];
  
  rv[key] = rv[key] || [];
  rv[key].push(obj[key]);
  
  return rv;
}, {});


console.log(res);

Important Note: This code snippet will always return data in array format, even if there is only one value. If you specifically require the exact format you mentioned, additional logic can be implemented as shown below. However, it is cautioned that this approach may introduce further complexity in the code in the future.

var data = [{"6":6.5},{"4":4.2},{"6":6.3}];

var res = data.reduce((rv, obj) => {
  var key = Object.keys(obj)[0];
  
  if (Array.isArray(rv[key])) {
    rv[key].push(obj[key]);
  } else if (rv[key] !== undefined) {
    rv[key] = [rv[key], obj[key]];
  } else {
    rv[key] = obj[key];
  }
  
  return rv;
}, {});


console.log(res);

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

Rails encountered a syntax error while attempting to parse JSON data, due to an unexpected character found at line 2, column 1

I'm a beginner when it comes to using AJAX in Ruby on Rails. What I'm trying to achieve is that when a user clicks on a link with the class .link (redirecting to an external site, for example www.google.de), it should send data - specifically the ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

Tips for accessing various JSON objects from a JSON document

My task involves extracting specific information from a JSON file using AJAX and jQuery. The structure of my JSON data is as follows: "Footwear": { "Adidas": [ { "id" : 0, &q ...

I'm looking to enhance my code by adding a new user login password. How can I achieve this?

Currently, I am in the process of adding another user and have been exploring various code snippets available on different websites. I decided to test the following example, which worked perfectly. However, I am now wondering how I can add an additional u ...

What is the procedure to reduce my final search result by 1?

When the search is triggered, I want to filter the images by name. However, the issue arises when trying to make everything disappear on filter addition. <ul id="list2"> <li class="in2"> An extra number is added ...

Python Scrap Data Project

I attempted to extract data using Xpath, but unfortunately, it was unsuccessful. My aim is for the code to retrieve information from specific columns on the website "https://www.destatis.de/DE/Themen/Gesellschaft-Umwelt/Bevoelkerung/Geburten/Tabellen/leben ...

I am encountering difficulties with importing Node modules into my Vue.js project

Having some trouble importing a node module via NPM in a Vue.js single file component. No matter which module I try to install, it always throws an error saying These dependencies were not found. I'm following the installation instructions correctly ( ...

What is the best way to incorporate a vanilla javascript function into a vue.js application?

Consider a vanilla JavaScript function like this: if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); i ...

Transfer a JSON object to a Java Class without relying on a servlet

I have a form in HTML where I collect user input and store it as an object in JavaScript. Here is how I am creating the object: var dataObject = { Name: getName(), Age : getAge() } Now, I want to send this object using Ajax to a b ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

"Visualizing data with Highcharts: Utilizing percentages in a basic bar chart

I am working on a basic 1-series bar chart with nominal values for each bar. While I am able to plot it with data labels and axis showing the value of each bar, my goal is to display the percentage of the total series on these labels while keeping the nomi ...

Difficulty encountered while duplicating NSMutableArray

My attempt to duplicate one array into another is causing an issue: NSMutableArray *itemsCopy = [[NSMutableArray alloc] initWithArray:self.items copyItems:YES]; Instead, I encounter the following error: *** Terminating app due to uncaught exception &apo ...

Tips to retrieve an Angular `value` from outside the module

customConfig.js angular.module("steam") .value("customConfig", { baseurl: "http://dev-back1.techgrind.asia/" }); To access the value outside the module, replace the " .." with customConfig.baseurl apiTest.js var frisby = require("frisby"); fris ...

Can Google's bot initiate JavaScript click events on a website and how can this be resolved?

Currently, we are facing an issue with the reviews on our website. In order to optimize page load speed on both desktop and mobile, we have decided to initially display only 10 reviews. After each button click by the user, the next set of 10 reviews is loa ...

A guide to using Powershell to extract specific data from a JSON file using a single parameter

I'm attempting to create a PowerShell script that can extract specific values from a large JSON file based on certain conditions. Below is a snippet of the JSON file and the PowerShell script I am using, but I'm not getting any values returned. H ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...

Design interactive images in NativeScript

I need assistance setting up clickable images in NativeScript. My goal is to arrange 5 images horizontally, and when one image is clicked, the images to its left should change their values. Here's what I've attempted: <Label col="0" row="0" ...

Can you link the source of an image to a local JSON file in Vue.js?

I currently have a local JSON file that contains an image. [{ "image": "/img/slider-first.jpg" }] I am importing this file into my component like so: const data = require('../assets/pets-data.json') Next, I'm trying to display the imag ...

Populating a dynamic array with values provided by the user

I'm new to shell scripting and currently working on creating an array where the user inputs a string x during runtime (currently using a static value for testing purposes). #!/bin/bash x="101:Redmi:Mobile:15000#102:Samsung:TV:20000#103:OnePlus:Mo ...

Customizing the placeholder font size in Material UI Autocomplete using ReactJS

Is there a way to change the placeholder font size for Material UI Autocomplete? https://i.stack.imgur.com/x71k2.png <Autocomplete multiple id="tags-outlined" options={top100F ...