Combining array of objects by various identifiers

I'm facing a situation like this:

const idMappings = {
// id: parentId
  "2": "1",
  "3": "1"
}

const inputData = [
  {
    id: "1",
    data: [1],
  },
   {
     id: "2",
     data: [2]
   },
   {
     id: "3",
     data: [3]
   },
   {
     id: "4",
     data: [4]
   }
]

const expectedOutput = [
  {
    id: "1",
    data: [1,2,3]
  },
  {
    id: "4",
    data: [4]
  }
]

Using the 'idMappings' array, I aim to create a configuration that will determine which object in the 'inputData' array should have merged data (objects without an id-parentId pair defined should remain unchanged). The code above serves as a better demonstration of what I'm trying to achieve. I've attempted some mappings but haven't achieved desirable results. Is there a more efficient way to define the 'idMappings' array to simplify this scenario? Any suggestions would be greatly appreciated.

Answer №1

To achieve this, utilize the reduce() method. Begin by creating an object that uses the id as the key. Eventually, you can transform it into an array using Object.values().

const ids = {
  // id: parentId
  "2": "1",
  "3": "1"
}

const input = [{
    id: "1",
    data: [1],
  },
  {
    id: "2",
    data: [2]
  },
  {
    id: "3",
    data: [3]
  },
  {
    id: "4",
    data: [4]
  }
]

const output = Object.values(input.reduce((acc, {
  id,
  data
}) => {
  if (id in ids) { // replace id with parent
    id = ids[id];
  }
  if (id in acc) {
    acc[id].data = acc[id].data.concat(data);
  } else {
    acc[id] = {
      id,
      data};
  }
  return acc;
}, {}));

console.log(output);

Answer №2

If you need to gather references from similar groups, consider using the following code:

const
    ids = { 2: "1", 3: "1" },
    input = [{ id: "1", data: [1] }, { id: "2", data: [2] }, { id: "3", data: [3] }, { id: "4", data: [4] }],
    output = Object.values(input.reduce((r, { id, data }) => {
        id = ids[id] ?? id;
        (r[id] ??= { id, data: [] }).data.push(...data);
        return r;
    }, {}));

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

If you want to manipulate the input array directly by cycling through it, consider using a method like the one shown below:

const input = [
  {
    id: '1',
    data: [1]
  },
  {
    id: '2',
    data: [2]
  },
  {
    id: '3',
    data: [3]
  },
  {
    id: '4',
    data: [4]
  }
]

const config = {
  2: '1',
  3: '1'
}

const merge = ({ input, config } = {}) => {
  for (const [childId, parentId] of Object.entries(config)) {
    const childIndex = input.findIndex(i => i.id == childId)
    const parent = input.find(i => i.id == parentId)
    parent.data.push(...input[childIndex].data)
    input.splice(childIndex, 1)
  }

  return input
}

console.log(merge({ input, config }))

Answer №4

the solution can be achieved in the following way:

let identifiers = { 2: "1", 3: "1" }
let inputData = [{ id: "1", data: [1] }, { id: "2", data: [2] }, { id: "3", data: [3] }, { id: "4", data: [4] }];
let keys = Object.keys(identifiers);
let objects = inputData.slice();//to preserve the original input
const result = objects.map(currentObject=>{
    let currentId = currentObject.id;
    if(keys.includes(currentId)){
        let updatedObject = objects.find(obj=>obj.id==identifiers[currentId])
        updatedObject.data.push(...currentObject.data)
    }
    return currentObject
})
console.log(result);

NOTE: slice() was used to avoid altering the original input

Answer №5

You can achieve the desired result by utilizing the combination of Array#reduce, Object.entries, and Array#map methods in the following manner:

const ids = { "2": "1", "3": "1" },
      input = [ { id: "1", data: [1], }, { id: "2", data: [2] }, { id: "3", data: [3] }, { id: "4", data: [4] } ],

output = Object.entries(
    input.reduce(
        (acc,{id,data}) =>
        ids[id] ?
        ({...acc,[ids[id]]:[...(acc[ids[id]] || []),...data]}) :
        ({...acc,[id]:[...(acc[id] || []), ...data]}),{}
    )
)
.map(([id,data]) => ({id,data}));

console.log( output );
//OUTPUT: [{"id":"1","data":[1,2,3]},{"id":"4","data":[4]}]

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

When attempting to retrieve the innerHTML of a <div> element within a <Script> tag, the value returned is undefined

Utilizing a masterpage to create a consistent header across all content pages, I encountered an issue on one page. I needed to retrieve the innerHTML of a div element and pass it to an input control on the same page in order to access the updated innerHTML ...

Is there a way to retrieve all active HTTP connections on my Express.js server?

In my express server app, I am implementing SSE (server send events) to inform clients about certain events. Below is the code snippet from my server: sseRouter.get("/stream", (req, res) => { sse.init(req, res); }); let streamCount = 0; class SS ...

Dealing with the problem of delayed image loading in AngularJS due to a setTimeout conflict

The issue: Upon page load, some images are still processing and not displaying (even though the image URLs are known). The resolution: To address this problem, a customized directive was developed to showcase a loading spinner as a placeholder until the i ...

encountering a problem with retrieving the result of a DOM display

private scores = [] private highestScore: number private studentStanding private studentInformation: any[] = [ { "name": "rajiv", "marks": { "Maths": 18, "English": 21, "Science": 45 }, "rollNumber": "KV2017-5A2" }, { "n ...

Error: Angular JS Service is undefined

I'm currently working on creating an array in my application that is universally accessible through services. Additionally, I have implemented ui-router in my application. In the app.js file, I define the service like this: myFamilyApp.service(&apos ...

Tips for implementing the same autocomplete feature across multiple form fields

Struggling to add multiple products and provide auto-suggest for each product name? You're not alone. It seems like the auto suggest feature is only working for the first product. Can anyone point out what's going wrong here? Here's my HTML ...

Encounter an error when reading a stream with a maximum timeout value set

I have encountered a challenge while trying to read and process large CSV files. Due to a rate limit in processing, I need to introduce a 1-minute delay between each request. Initially, I attempted to use set timeout, but discovered that there is a limitat ...

A step-by-step guide on how to repeatedly reload a nextJS page using recursion and display an error page once the

I've been experimenting with a recursive page reload function that looks like this: export const refreshPage = (count)=>{ if (count <= 0){ // window.location.reload(); console.log("blue"); return }else { console.log(& ...

Detecting errors on the client side with JSON payload in Next.js and a personalized server

Working with Next.js and a custom Express server, I've encountered an issue regarding basic API error handling. I have set up a simple error handling middleware that looks like this: app.use((err, req, res) => { res.status(400).send(message); ...

The error message "Google Heatmap API - visualization_impl.js:2 Uncaught (in promise) TypeError: Cannot read property 'NaN' of undefined" was encountered while using the

I'm currently working on a project that involves utilizing a JSON data structure like the one shown below: [ { "lat": 53.1522756706757, "lon": -0.487157731632087, "size": 63, "field": "TestField", ...

Storing items in localStorage in the same order they were added

I am having an issue with sorting localStorage items by the order they were added. Despite my code working to add items to the localStorage array and display them as HTML, I am encountering a problem with the order of the items. When I add a 3rd item to t ...

Dots are used to indicate overflow of title in React Material UI CardHeader

Is there a way to add ellipsis dots to the title in my Cardheader when it exceeds the parent's width (Card width)? Here is what I have attempted so far: card: { width: 275, display: "flex" }, overflowWithDots: { textOverflow: &apo ...

A Guide to Filtering MongoDB Data Using Array Values

I am trying to extract specific data from a document in my collection that contains values stored in an array. { "name": "ABC", "details": [ {"color": "red", "price": 20000}, {" ...

What is the best way to create a smooth transition for a bootstrap navbar in chrome, toggling from right to left on

I have successfully modified the bootstrap navbar to toggle from right to left instead of top to bottom using the following code: For HTML- <nav class="navbar navbar-inverse" role="navigation" style="height: 55px; padding-top: 2px; background-color: # ...

I am having trouble deactivating an HTML button using my JavaScript function

I have been working on a feature where a button in HTML is supposed to be disabled until a specific textbox is filled out. Once the textbox has content, the button should become enabled and save the user's name along with their score from a previous g ...

Updating a database on ASP.NET without the need to refresh the page

We are developing a user-friendly application with ASP.NET MVC that focuses on uploading pictures and rating them. The app includes two voting buttons, "like" and "dislike". https://i.sstatic.net/Z3dp5.png Whenever the like button (green) is clicked, the ...

Organize the HTML output generated by a PHP array

There must be a simple solution to this, but for some reason, it's escaping me right now. I've created custom HTML/CSS/JS for a slider that fetches its content from an array structured like this: $slides = [ [ 'img' = ...

Jquery Visualization Chart not displaying

I am struggling to get the jquery visualization to work properly. Although the table and caption appear fine, there is no data showing up in the chart. I've carefully followed the example and searched for any issues, but I can't identify what&apo ...

Retrieving the ID and value of a specific dropdown list using jQuery from an array of dropdown lists

My HTML structure looks like this: <?php foreach($active_brand as $brand) { ?> <select name="selector" id="selector"> <?php foreach($options as $option) { ?> <option <?php if($brand['State'] == $option) { ?& ...

When incorporating express.static(), the Express .use() callback may be triggered multiple times

I'm in the process of verifying a user's identity, and once that is confirmed I aim to add them as a new user in my personal database using the information provided by the authentication server. The issue at hand is that the function createNewAc ...