Merge JSON entries with identical names

Currently, I am delving into the world of javascript and honing my skills in working with JSON.

I have a JSON file that presents a challenge - how can I consolidate entries with the same name under one single entry? Any ideas on how to achieve this?

Original JSON Data

[{
    "name": "1.date.17-Nov-18",
    "size": 1000,
    "imports": ["1.location.HOUSTON", "1.person.JOHN"]
},
{
    "name": "1.date.17-Nov-18",
    "size": 1000,
    "imports": ["1.location.MIAMI", "1.person.BEN", "1.person.JOHN"]
},
{
    "name": "1.date.18-Nov-18",
    "size": 1000,
    "imports": ["1.location.UBER", "1.person.JOHN"]
}
]

Desired Output

[{
    "name": "1.date.17-Nov-18",
    "size": 1000,
    "imports": ["1.location.HOUSTON", "1.person.JOHN", "1.location.MIAMI", "1.person.BEN"]
},
{
    "name": "1.date.18-Nov-18",
    "size": 1000,
    "imports": ["1.location.UBER", "1.person.JOHN"]
}
]

If you have any insights or suggestions on how to tackle this issue, please share them. Thank you!

Answer №1

We utilize an object to maintain a record of the names and then proceed to iterate through the data array by employing the forEach method.

During this process, we validate whether the name of the item has been encountered previously. If it has, we combine their respective imports. Otherwise, we simply add the item to the object.

To ensure no duplicate entries within the imports, we employ a Set which effectively eliminates duplicates, following which we transform it back into an array utilizing the spread operator ....

Finally, we use Object.values to retrieve the consolidated data without the names acting as keys.

const result = {};
const data = [{"name":"1.date.17-Nov-18","size":1000,"imports":["1.location.HOUSTON","1.person.JOHN"]},{"name":"1.date.17-Nov-18","size":1000,"imports":["1.location.MIAMI","1.person.BEN","1.person.JOHN"]},{"name":"1.date.18-Nov-18","size":1000,"imports":["1.location.UBER","1.person.JOHN"]}];

data.forEach(item => {
  if (item.name in result) result[item.name].imports = [...new Set([...item.imports, ...result[item.name].imports])];
  else result[item.name] = item;
});

console.log(Object.values(result));

Answer №2

Transform the array into a Map and remove duplicate imports.

const data = [
  {
    name: '1.date.17-Nov-18',
    size: 1000,
    imports: ['1.location.HOUSTON', '1.person.JOHN'],
  },
  {
    name: '1.date.17-Nov-18',
    size: 1000,
    imports: ['1.location.MIAMI', '1.person.BEN', '1.person.JOHN'],
  },
  {
    name: '1.date.18-Nov-18',
    size: 1000,
    imports: ['1.location.UBER', '1.person.JOHN'],
  },
];

console.log(
  Array.from(data.reduce((m, o) => (
      m.has(o.name)
        ? m.get(o.name).imports.push(...o.imports)
        : m.set(o.name, { ...o }),
      m), new Map()).values(),
    (v) => ({ ...v, imports: [...new Set(v.imports)] }))
);

Answer №3

Here is a solution you can experiment with:

const data = [{"name":"1.date.17-Nov-18","size":1000,"imports":["1.location.HOUSTON","1.person.JOHN"]},{"name":"1.date.17-Nov-18","size":1000,"imports":["1.location.MIAMI","1.person.BEN","1.person.JOHN"]},{"name":"1.date.18-Nov-18","size":1000,"imports":["1.location.UBER","1.person.JOHN"]}];

const result = data.reduce((acc, {name, size, imports}) => {
  acc[name] =  acc[name] || {name: name, size: size, imports: []};
  acc[name].imports = [...new Set([...acc[name].imports, ...imports])];
  
  return acc;
}, {})
console.log(Object.values(result));
.as-console-wrapper{min-height: 100%!important; top: 0}

Answer №4

To tackle this problem, you can utilize the power of Array.prototype.reduce. Since you are just beginning to grasp JavaScript concepts, I will provide a detailed explanation for the solution. Give this code snippet a try:

const data = [{
    "name": "1.date.17-Nov-18",
    "size": 1000,
    "imports": ["1.location.HOUSTON", "1.person.JOHN"]
},
{
    "name": "1.date.17-Nov-18",
    "size": 1000,
    "imports": ["1.location.MIAMI", "1.person.BEN", "1.person.JOHN"]
},
{
    "name": "1.date.18-Nov-18",
    "size": 1000,
    "imports": ["1.location.UBER", "1.person.JOHN"]
}];

let res = data.reduce((acc, curr) => {
  if (acc[curr.name] === undefined) {
    acc[curr.name] = curr;
  } else {
    acc[curr.name].imports.push(...curr.imports);
  }
  return acc;
}, {});

res = Object.values(res);

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

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 causes the discrepancy in results between Javascript sha1 and PHP5 sha1 when generating hashes for utf-8 strings?

I'm facing an issue with utf-8 characters in a string. The PHP sha1 and Javascript sha1 are generating different codes for the same string "abc艾". Can anyone assist me with this? Thank you in advance. PHP code: $str = "abc艾"; $result = sha1($st ...

At the initialization of my application, Vue Router effortlessly loads all my dynamically imported components

My Vue application is utilizing lazy loading router setup with the following configuration: router.ts const Grid = () => import(/* webpackChunkName: "grid" */ './views/grid/Grid.vue'); const Calendar = () => import(/* webpackChun ...

Unable to retrieve output from function

Currently, I am in the process of developing a straightforward script designed to retrieve a JIRA Case ID once an issue has been submitted to JIRA. One important component is the creation of an issue function, which takes JSON parameters from a RESTful we ...

Tips for retrieving user input and displaying it on an HTML page

I have encountered an issue with displaying user input in a table. The code for the table display is as follows: <tr ng-repeat="user in users" ng-class-even="'bg-light-grey'" ng-if="isLoading==false"> <td> ...

Angular: Selecting all checkboxes outside of an ng-repeat loop

Project Overview In my project, there is a system for managing small product orders. Users have the ability to add order lines and attach one or more products to each order line. While it may be uncommon to have multiple products on the same order line, t ...

Finding a way to access a specific range of bytes within a unique_ptr byte array

Update Decided to try a different approach for reading in the data, as shown below: Original post Although I have some experience coding in Unreal, I'm relatively new to C++. I'm currently working on a File Parser as a standalone solution and f ...

Vue: Child component not rendering string prop

Hey there, I'm currently exploring the ins and outs of Vue and diving into its one-way data bind model, component registration, and passing props. Within my index.js file, I've set up my parent component to render a single child component for no ...

Issues with Chrome DevTools script blackboxing functionality not functioning as intended

Recently, I decided to explore the new feature in Chrome Devtools called "blackboxing a script". An informative article on script blackboxing functionality in Chrome Devtools Curious about the impact of blackboxing a script? Exceptions thrown from l ...

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

What is the process for encoding an image as a Base64 string within a file?

I need help with selecting multiple images and converting them into Base64 strings. I have already stored the images in an array, but now I am struggling to convert them. Here is my code: $("input[name=property_images]").change(function() { var name ...

Is it possible to manipulate the GET API response using the Selenium WebDriver or a REST API in order to set the response body as null, for the purpose of testing error handling on the

Is there a method to manipulate the response of a GET API request using either Selenium WebDriver or a REST API in order to set the response body to null and test error handling on the UI? ...

I am experiencing an issue where my ajax code is unable to display the

After spending countless hours trying to make this work, I find myself stuck. I've set up a simple guestbook page and have created this code to generate a JSON file: <?php /* Constants for database settings */ define("DBHOST", "localhost"); defin ...

Storing a JSON response in an NSPredicate with objective C: A step-by-step guide

One of the challenges I'm facing is passing values in the first cell using another view controller I also need to verify existence by utilizing NSPredicate If the condition is satisfied, then a data reload is required I would appreciate assistance wi ...

Why won't the thread stop in Tomcat?

Recently, I encountered an issue with my Java multi-threaded program running on a Tomcat server. While the threads were in various states - some executing tasks, some waiting for something to return - I had to stop the server abruptly. Upon doing so, I r ...

Use a spy to mock a component method using karma and jasmine

Encountering this error message during testing: ERROR: 'Error during cleanup of component' The issue stems from the following code snippet : ngOnDestroy(){ methodCallToMock() } To address this, I need to mock the methodCallToMock() functi ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...

Unable to invoke modal popup from master page on child page

Incorporating a modal popup to display a login box has brought up an interesting challenge. The modal popup is situated in the master page and connected to a LogIn link. However, now there is a need to invoke the same modal popup from a child page using a ...

What is the best method to retrieve an array similar to this from MySQL using PHP?

I currently have a table structured as follows- event (id,name,date) My desired result set looks like this $result = array( '1'=>array( array('id'=>2,'name'=>'football match','date'= ...

Sending Emails with AngularJS

Exploring AngularJs has been a delightful experience for me, and I recently stumbled upon a fantastic plugin for Angular called angular-http-auth. This plugin allows you to seamlessly integrate an identification system. Does anyone know of a similar resou ...