Combining the data of an object with an array of objects while ensuring that existing key values are not replaced

How can you transform the following array and object:

var array = [{key: [3]}, {key1: [3]}, {key1: [3]}]
var object = {key1: [3], key2: [3]};

into this output:

{key: [3], key1: [9], key2: [3]}

All "key" values represent userIds like "LQVjUacPgK" as shown in the example object below.

[N] = an array of N objects each containing around 10 key-value pairs.

N = {obj, obj, obj};

obj = {_account: "JDQEPxoy3ktZRP9VEzAMtXLa7rXXedhQ4bARq"
_id: "oQER3vznDwikxm1wdLzJFdVjKL6XomcORMxDL"
amount: 170
category: Array[2]
category_id: "21003000"
date: "2015-06-09"Object
type: Object
userId: "LQVjUacPgK"}

Currently, the process being used is:

var test = _.reduce(_.flatten(array.concat([object])),function(a,b){
     return _.extend(a, b);
       });
    }
};

However, the current result is different than desired:

console.log(test)//{key: [3], key1: [3], key2: [3]}

The main issue lies with the fact that key1 has varying values across the objects. The goal is to merge these values accordingly so that key1: [9].

Answer №1

This answer takes a different approach, avoiding the use of a reduce operation and opting for a simple for-each loop:

const data = [{id: [3]}, {id1: [3]}, {id1: [3]}]
const newData = {id1: [3], id2: [3]};

data.forEach((item) => {
  Object.keys(item).forEach((key) => {
//        newData[key] = [(newData[key] || [])[0] || 0 + item[key][0]];
      newData[key] = (newData[key] || []).concat(item[key]);
  });
});

console.log(JSON.stringify(newData)); // {"id1":[3,3,3],"id2":[3],"id":[3]}

Answer №2

Similar to Jane's response (also no underscore), this code snippet generates a new object instead of altering the existing object Object:

let arr = [{name: [3]}, {name1: [3]}, {name1: [3]}]
let obj = {name1: [3], name2: [3]};

let result = arr.concat([obj]).reduce(function(previous, current) {
  Object.keys(current).forEach(function(key){
    if (previous.hasOwnProperty(key)) {
      previous[key][0] += current[key][0];
    } else {
      previous[key] = current[key];
    }
  });
  return previous;
},{});

console.log(JSON.stringify(result));  // {"name":[3],"name1":[9],"name2":[3]}

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

learn how to implement local storage for a to-do list application using JavaScript

How do I implement the storage property in this code snippet? The current code is not functioning correctly and resets after each page refresh. Please review my code at the following link: https://jsfiddle.net/74qxgonh/ let values = []; // Accessing Form ...

What could be causing my jQuery click event to behave as if I triggered a click on the parent element?

I have created multiple child divs within a parent div. All the divs are positioned, with the parent div set to absolute and the child divs set to relative. The z-index of the parent div is 400, while the child divs have a z-index of 500. However, when I ...

Adjusting the properties of an element with Javascript

My goal is to dynamically set the value of a parameter within a <script> element using JavaScript. I am using the Stripe checkout.js and I want to populate the Email input field with a value obtained from another text box on the page. Here's how ...

Leverage Async/Await in React.js with the Axios Library

Recently, I came across an interesting article on Medium titled How to use async/await with axios in react The article discussed making a simple GET request to a server using Async/Await in a React.js App. The server returned a JSON object at /data with t ...

How can I design a form that resembles the sign-in form used by Google?

Currently, I am in the process of creating a contact form for a website that is inspired by the design of Google's material sign-in form. I have successfully implemented an effect where clicking on the input field causes the label to change its posit ...

The Primevue Chart failed to display

I'm having some trouble displaying a Chart using Primevue components. It's built on the chart.js library. Currently, I have a basic Vue component set up as follows: <template> <div class="p-chart"> <h2>Chart:< ...

Instead of using setTimeout in useEffect to wait for props, opt for an alternative

Looking for a more efficient alternative to using setTimeout in conjunction with props and the useEffect() hook. Currently, the code is functional: const sessionCookie = getCookie('_session'); const { verifiedEmail } = props.credentials; const [l ...

JQuery functionality is disrupted by the update panel on the master page

I'm facing an issue with three anchors on the page - one for time in, one for time out, and one for the menu. Initially, everything works fine when the page loads for the first time. However, clicking on the time in or time out button causes the menu ...

Track the status of an extensive MySQL query using PHP

Looking for a way to show the progress percentage of a lengthy mysql query using php? Well, you can create a filter button in your database that triggers a javascript function through ajax and calls a php file. function show(){ $.ajax({ ...

Incorporating navigation controls into a modal window

I have successfully created a sign-in modal, but now I'm looking to include buttons at the top. One button should redirect users to register/sign up, and the other button should lead them back to the sign-in modal, as shown in the image I've link ...

To extract three records from storage and store them in the dbResult using a promise join technique

How can I efficiently retrieve and store 3 records in dbResult using promise join? Currently, I have code that retrieves a single record as shown below: req.oracleMobile.storage.getById(registry.getIncidentPhotoStorageName(), incident_id + '_01&apos ...

Guide to setting a callback function on a submission button in bootstrap

Utilizing a bootstrap modal dialog for the user registration form can be accomplished with the following code: <form> <div class="modal-dialog" role="document"> <div class="modal-content"> ...

React dynamic dropdown selection based on previous dropdown values

I have implemented 3 react input fields that are populating data to a useState Hook <FormControl fullWidth> <InputLabel>Primary Goal</InputLabel> <Select ...

Google Maps API displaying empty spots instead of markers

I am facing an issue with my webpage where the Markers are not showing up, despite troubleshooting for many hours. The parsing php file has been confirmed to be working. Below is the code: <script src="https://maps.googleapis.com/maps/api/js">< ...

In PHP, a boolean variable will not display on the webpage when echoed

I am facing an issue with my PHP code where certain variables are not being echoed properly in the generated JavaScript. The code is designed to check if specific values are assigned in the $_GET global array and assign default values if they are not prese ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

Utilizing jQuery's extend method for object inheritance in a function

I've been experimenting with using jquery extend to simulate inheritance, but it seems that it only works with objects based on my testing. My goal is to achieve the following: var baseDefinition = function() { var self = this; self.calc1 = ...

Upon returning, the C string function argument is found to be NULL

Currently, I am working on a function that needs two strings as inputs and returns two different strings as outputs. My approach was to use an int for the error code and have two pointers to C strings as arguments. This is how I implemented it: int anneal ...

Adjustable Footer Size with Minimum Size Constraint

On my webpage, I have a footer that is not fixed in place. Currently, the page's content does not require scrolling, and the footer occupies about 25% of the browser window at full screen on a 1920 x 1080 display. The footer's contents are aligne ...

What is the best approach to bring a button into focus after it has been enabled in a React.js application

I'm a beginner in react js and I'm attempting to set the focus on a button after filling out all input fields. However, despite programmatically enabling the button with autoFocus implemented, I am unable to focus on it. return ( < ...