Looking to combine two objects and generate an array of their values?

I am faced with a scenario where I have two objects that share the key and value name of DateYMD. My intention is to merge these two objects and generate a new object from them.

Here is the data from the current objects :

[{
          "Id": "1",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T08:00:00",
          "bookTimeTo": "2024-12-05T13:00:00"
        },
        {
          "Id": "2",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T14:00:00",
          "bookTimeTo": "2024-12-05T18:00:00"
        }]

I attempted to use the Object.assign method to accomplish this task, but it did not yield the expected results.

The desired output should look like this :

{
         "date": "2024-12-05T00:00:00",
         "DateYMD": 20241205,
         "Id": ["1","2"],
         "bookTimeFrom": ["2024-12-05T08:00:00", "2024-12-05T14:00:00"],
         "bookTimeTo": ["2024-12-05T13:00:00", "2024-12-05T18:00:00"]
     }

Answer №1

Sort values into sets based on object keys and then transform the sets into arrays. Optionally arrange keys depending on whether the final value is an array or not.

const arr = [{
          "Id": "1",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T08:00:00",
          "bookTimeTo": "2024-12-05T13:00:00"
        },
        {
          "Id": "2",
          "date": "2024-12-05T00:00:00",
          "DateYMD": 20241205,
          "bookTimeFrom": "2024-12-05T14:00:00",
          "bookTimeTo": "2024-12-05T18:00:00"
        }]


const sets = arr.reduce((r, obj) => (Object.entries(obj).forEach(([k, v]) => (r[k] ??= new Set).add(v)), r), {});
const out = Object.entries(sets)
  .sort(([_,a], [__,b]) => (a = +(a.size>1), b = +(b.size>1), a - b))
  .reduce((r, [k, v]) => (r[k] = v.size > 1 ? [...v] : [...v][0], r), {})
  

console.log(out);

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

What is the best way to access a nested promise element in Protractor?

I've recently put together a function in protractor that I'd like to share: function findChildElementByText(parentElement, tagName, textToSearch) { return parentElement.all(by.tagName(tagName)) .then((items) => { items.map( item ...

The speed of C# Socket.send function is incredibly sluggish

Utilizing the Socket class, I am transmitting image data in byte array to a third-party program that is operating on the same computer (thus eliminating any potential connection issues). My application is quite basic, as I solely rely on the synchronous ...

Implementing a JavaScript function that uses the AJAX method to confirm and update

I am currently attempting to update a database using the JavaScript confirm() function in combination with AJAX. My goal is to have "accepted_order.php" run if the user clicks "OK," and "declined_order.php" run if the user clicks "Cancel," all without caus ...

Mastering the Art of Revealing and Concealing

I stumbled upon a great demonstration on reversing the Hide and Show functionality at https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show <!DOCTYPE html> <html> <head> <meta name="viewport" content="width ...

Using Vue.js to bind a class to a component through a prop

Incorporating a color attribute via prop into a component is my current challenge. This attribute will determine the background color of the component, with the available options being 'red' and 'blue'. The structure of the component i ...

What is the best way to switch between search results shown in an li using AngularJS?

Looking for a way to toggle a list that appears when a user searches in my app. I want the search results to hide when the search bar is closed. How can I achieve this? I think Angular might be the solution, but I'm stuck on how to implement it. I tri ...

Sending back an array within the onOpen function

I am currently in the process of developing a chat application. At this stage, users are able to send messages to each other and I have successfully stored these messages in my database. Now, my objective is to display the stored messages from the database ...

Tips for resolving the trigger problem with onChange in the PinInput Component of chakra-ui

The PinInput Component's onChange event is not functioning properly with the value in Chakra-UI. This issue causes the focus to automatically shift to the next input even when the value hasn't changed. For instance, when attempting to set the st ...

Transforming attributes into a JSON format

Click here to view my JSFiddle example function testing() { foo = canvas.getObjects(); bar = JSON.stringify(canvas.getObjects()); console.log(foo); console.log(bar); } After examining my JSFiddle link above, it appears that JSON.stringify() is al ...

Verify whether the function is operational using Google Apps Script and Google Web Apps

I have created a basic Google Apps Script that links to IFTTT on my phone and sends SMS messages. Now, I am attempting to create a more user-friendly interface by deploying the script as a Google Web App. The concept is simple: click a button, see "Sending ...

Issue with Vue: After removing an item from a v-for list, there is a remnant

Can you help me solve this issue with my Vue component setup? I have a list of components, each consisting of a preview canvas, a name, and a delete button. These components are stored in Vuex. For example, the list could look like this: | [W] Item 1 ...

What are the steps for managing (filtering and organizing) an array of items in a mongodb collection?

Within my collection, I have the following items: { "_id" : ObjectId("5c0325eec104041f38a6f9ec"), "total_distict_words" : 137, "items" : [ { "first" : 1 }, { "another" : 3 }, { ...

Place a drop-down menu inside the input box

Struggling with this issue, I've come across various messy solutions, but I'm determined to find a cleaner one. What I'm looking for is an input field that includes a dropdown selection on the left side. This is essentially what I have in m ...

Discovering the value of a variable within an object using JavaScript

Here is the code snippet I am working with: for (var i = 0; i<ke.length; i++) { var ar = ke[i]; var temp = {ar :(n[a])}; //how to resolve a console.log(temp); } The 'temp' object is supp ...

Adding elements to a JSON array in Javascript

Seeking assistance on updating a JSON array. var updatedData = { updatedValues: [{a:0,b:0}]}; updatedData.updatedValues.push({c:0}); This will result in: {updatedValues: [{a: 0, b: 0}, {c: 0}]} How can I modify the code so that "c" becomes part of ...

Is there a way to toggle the visibility of a div when transitioning from one page to another and then returning to the original page?

I need help with managing content on my HTML pages. I have certain information on the Home page that should remain unchanged when the page is refreshed. However, I would like to be able to show or hide specific divs or sections of HTML when navigating ba ...

Is storing Vuex state in sessionStorage a secure practice?

I am currently developing a web app with Vue.js/Vuex, but I am facing an issue where the state is lost when the user refreshes the page. I have attempted to address this by persisting some states in sessionStorage, however, I have come to realize that use ...

Update the image using JavaScript whenever the button is pressed

Looking for a way to change the image every time the "next" button is clicked. Currently, the code only shows the last image from the 'book' array after a single click of the 'next' button. Is there a solution to this issue? HTML code: ...

Develop two varieties of user account models using Mongodb/Mongoose

Currently, I am utilizing mongoose in my nodejs project and I am seeking advice on creating a MongoDB schema that caters to two different user types: employees and clients. Both of these users will be registering through the same page (I am implementing pa ...

Is it possible to render array items into separate divs using the .map() method without displaying commas?

After extensive searching, I have only come across solutions that involve using .join() to combine the items into a single string. const createCard = () => { const pokemonTypes = ['grass', 'fire', 'water']; return ...