Combine values within a single property of an object using the reduce method

My array consists of objects structured like this:

let array = [{
    "Age": 20,
    "Name": "Kevin"
}, {
    "Age": 15,
    "Name": "Alfred"
}, {
    "Age": 30,
    "Name": "Joe"
}];

I am aiming to transform it into an object with combined values like this:

{
    "Age": '20, 15, 30',
    "Name": 'Kevin, Alfred, Joe'
}

When attempting the following reduce function:

let r = array.reduce(function(pV, cV) {
    Object.keys(cV).map(function(key){
        pV[key] = (pV[key] || [])concat(cV[key]);
    });
    return pV;
},{});

console.log(r); // { "Age": [20, 15, 30], "Name": ['Kevin', 'Alfred', 'Joe'] }

Alternatively, I tried another approach:

let r = array.reduce(function(pV, cV) {
    Object.keys(cV).map(function(key){
        pV[key] = (pV[key] || '') + ', ' + cV[key];
    });
    return pV;
},{});

console.log(r); // { "Age": ', 20, 15, 30', "Name": ', Kevin, Alfred, Joe' }

I'm uncertain which method will give me the desired outcome. Any suggestions on how to achieve my goal?

Answer №1

Your second approach is almost there, just remember to ensure that the comma does not show up initially. You can easily achieve this using a ternary operator:

let result = array.reduce(function(previousValue, currentValue) {
  Object.keys(currentValue).map(function(key){
      previousValue[key] = (previousValue[key] ? (previousValue[key] + ", ") :  '') + currentValue[key];
  });
  return previousValue;
},{});

Answer №2

If you want to explore an interesting approach, consider using the .reduce() function in conjunction with Object.keys

let products = [{
    "Price": 50,
    "Name": "Shoes"
}, {
    "Price": 30,
    "Name": "Hat"
}, {
    "Price": 100,
    "Name": "Jacket"
}];

let finalResult = products.reduce((currentProduct,resultingProduct) => {
Object.keys(currentProduct).forEach(key => {
if(!resultingProduct[key]){
resultingProduct[key] = currentProduct[key];
} else {
resultingProduct[key]+= ", " + currentProduct[key];
}
})
return resultingProduct;
},{});

console.log(finalResult);

Answer №3

In my opinion, I find the use of `reduce` in this context to be unnecessary as it essentially functions as a loop:

let result = {};
for (const currentValue of array) {
    for (const key in currentValue) {
        result[key] = (result[key] || []).concat(currentValue[key]);
    }
}

If we were to take a more functional approach and utilize `map` effectively, I would reverse the order of iteration like so:

let result = {};
for (const key of ["Age", "Name"]) { // or Object.keys(array[0])
    result[key] = array.map(function(currentValue){
        return currentValue[key];
    }).join(", ");
}

Answer №4

Another approach you can take is as follows.

 array.reduce((a,n)=>{
 a.Age =  a.Age+','+n.Age;
a.Name = a.Name+','+n.Name;
return a;
});

Please note that this method will modify the actual array of objects. If this is not your intention, consider cloning the object before using reduce.

To clone the array, I used

JSON.parse(JSON.stringify(array))
, but feel free to use your preferred method for deep cloning.

JSON.parse(JSON.stringify(array)).reduce((a,n)=>{
 a.Age =  a.Age+', '+n.Age;
a.Name = a.Name+', '+n.Name;
return a;
}) 

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

Ways to delete a class if it currently exists?

Is there a way to manage multiple toggle classes within a single div? It can be frustrating when clicking the maximize or close button triggers the minimize function as well. How can this situation be addressed? Is there a way to manage multiple toggle cl ...

Using jQuery to show text upon hover using a `for` loop

I'm currently working on a webpage and incorporating a feature where hovering over specific div elements triggers the display of certain text in another div. There are 5 elements that I want to make hoverable and show text upon interaction. After imp ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...

Inaccurate Feedback on Maquest Direction Route API

Currently, I am in the process of implementing the MapQuest API Direction Routing function on my website. However, upon submitting a request to the API, it is returning inaccurate routing points between two destinations. Here is the request form that I am ...

scrolling through a list using .slice choosing an excessive amount of items

Is it possible to create a dynamic pager that can be customized using parameters from the URL? I have noticed that when I hardcode the perTime variable, everything works fine. However, as soon as I try to use a parameter from the URL, the page starts behav ...

Prevent legend strike-through on click in Vue Chart.js

Recently, I made the transition from vue 2 to vue 3 on my website and part of that process involved updating vue-chartjs and chartjs too. However, after modifying the legend text of my pie chart using the generateLabels option (as seen below), the striket ...

How can I generate dynamic JSON objects from arrays in a spreadsheet by looping through and filtering out any empty values

(A few hours later, I revised the examples for better clarity, showing current and desired output) I am dealing with a spreadsheet containing thousands of rows of data, each row consisting of about 30 columns. New rows are added daily without any removals ...

Accessing a specific child div within a parent div using JavaScript and CSS

Struggling to target and modify the style of the child div within id="videoContainer" <div id="videoContainer"> <div style="width: 640px; height: 360px"> <------- this is the target <video src ...

Implement a customized toString method for components in ReactJS

Looking to modify the toString method of a class component in reactjs? Check out the code snippet below class C1 extends React.Component{ render(){ return ( <div> {C2.toString()} </div> ) } } class C2 extend ...

Throw an error if the entry is not found in the Firebase database

I have an array containing various objects. Users should be able to access all objects using moduls/, and a specific one with moduls/$id. However, if the requested modul does not exist, the database should return an error to inform the client that there is ...

If the visitor navigated from a different page within the site, then take one course of action; otherwise

How can I achieve the following scenario: There are two pages on a website; Parent page and Inside page. If a user navigates directly to the Inside page by entering the URL or clicking a link from a page other than the Parent page, display "foo". However, ...

Error encountered by React context: TypeError - Attempting to iterate over an object that is not iterable (unable to access property

I'm encountering this error: TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator)) whenever I attempt to handle state using useContext. The purpose here is to initialize "tokens" as an empty array [] on page load, and then ...

Difficulties arising when trying to convert latitude and longitude coordinates to xyz for camera rotation within Three.js

Currently, I am working on a JavaScript application that allows users to design their own closet. My goal is to enable smooth rotation of the closet without changing the distance from the camera to the closet. While it would be simple to rotate the object ...

Vue for Number Crunching

Learning vueJS is quite new to me. I am attempting to capture two input values, add them together, and display the result. I have encountered a strange issue where when subtracting number1 from number3, multiplying number1 with number2, or dividing number ...

Prevent the mouseup event in jQuery when the mouse has previously been moved

I have a div with a row of span buttons displayed horizontally. Since there are too many buttons to fit on the screen, I want to enable the user to click and drag the entire row of buttons. However, my challenge is to ensure that the button's mouseup ...

Please tap to dial: Access to navigation is restricted

Trying to add a click-to-call link with the following code: <a href="tel:+4912345678912">Tel: +4912345678912</a> Despite Google developers saying it should work, major mobile browsers are blocking the navigation when clicking on the link. It ...

Browserify pulls in entire module even if only specific parts are utilized, such as react-addons

I am currently using Browserify to bundle my server-side react.js code for the client. There is a concern that utilizing a module from an npm package may result in the entire package being bundled by Browserify. Question: Will require('react-addons& ...

Prevent the submission of the form if the textfield does not contain any

Is there a way to prevent form submission when a textfield is empty? Currently, my script allows for new empty records to be inserted into the database even when the textfield is empty. $(document).ready(function(){ $("#form1").on('submit', ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

Issue with webcomponents-lite.js file

Encountering this particular error message in the console while attempting to run the application: webcomponents-lite.js:64Uncaught TypeError: Cannot read property 'getAttribute' of null at webcomponents-lite.js:64 at Object.549 (webcomp ...