Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate?

Transform:

[
  {
     "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60",
     "planning":[
                   {
                   "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84",
                   "start":2016-01-01
                   },
                   {
                   "uuid":"37994EE3-F7E5-4199-A160-6D0B04D287D9",
                   "start":2016-01-02
                   }
                ]
  },
  {
     "uuid":"6BF57C74-F111-4901-A1C3-17E3B094C37E",
     "planning":[
                   {
                   "uuid":"21E386E9-0527-4EC2-81B5-A4F01B780B46",
                   "start":2016-03-01
                   },
                   {
                   "uuid":"D590A52C-DC9B-448E-A157-504CCA13FB45",
                   "start":2016-04-02
                   }
                ]
  }
]

to:

[
  {
     "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60",
     "planning":{
                   "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84",
                   "start":2016-01-01
                }
  },
  {
     "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60",
     "planning":{
                   "uuid":"37994EE3-F7E5-4199-A160-6D0B04D287D9",
                   "start":2016-01-02
                }
  },
  {
     "uuid":"6BF57C74-F111-4901-A1C3-17E3B094C37E",
     "planning":{
                "uuid":"21E386E9-0527-4EC2-81B5-A4F01B780B46",
                   "start":2016-03-01
                }
  },
  {
     "uuid":"6BF57C74-F111-4901-A1C3-17E3B094C37E",
     "planning":{
                "uuid":"D590A52C-DC9B-448E-A157-504CCA13FB45",
                "start":2016-04-02
                }
  }
]

I have attempted the code below, but the value of planning is always the first item's value. This code removes the current planning item's value.

var i= 0;
angular.forEach(data, function(value, key){
  if(value.planning.length>0){
    angular.forEach(value.planning, function(planningvalue, planningkey){
      $scope.out.push(value);
      $scope.out[i].planning=planningvalue;
      console.log($scope.out[i]);
      i=i+1;
    });
  }
});

Thank you

Answer №1


let results = [];

data.forEach((item) => {
  let id = item.uuid;
  item.planning.forEach((plan) => {
    results.push({ uuid: id, planning: plan});
  });
});

Check out the demo here

Answer №2

This could be the solution:

const information = [{
  "id": "EE877ABD-932F-4B4C-AB23-B324363B0B60",
  "schedule": [{
    "id": "6D680178-9B05-4744-A004-163D4B3E1E84",
    "date": "2016 - 01 - 01"
  }, {
    "id": "37994EE3-F7E5-4199-A160-6D0B04D287D9",
    "date": "2016 - 01 - 02"
  }]
}, {
  "id": "6BF57C74-F111-4901-A1C3-17E3B094C37E",
  "schedule": [{
    "id": "21E386E9-0527-4EC2-81B5-A4F01B780B46",
    "date": "2016 - 03 - 01"
  }, {
    "id": "D590A52C-DC9B-448E-A157-504CCA13FB45",
    "date": "2016 - 04 - 02"
  }]
}];

const processedData = information.reduce((accumulator, current) =>
  accumulator.concat(current.schedule
    .map(item => Object.assign({}, current, {
      schedule: item
    }))
  ), []
);

console.log(processedData)

Answer №3

Suppose the data array holds your original data, while the data2 array will store the processed information.

let data2 = [];
data.forEach((item) => {
  item.planning.forEach((plan) => {
    let copyData = Object.assign({}, item); // Make a copy of the outer object in the main array and replace the planning array with one of its containing objects.
    copyData.planning = plan;
    data2.push(copyData);
  });
});
console.log(data2);

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

Switching the destination for routing within a program

I'm trying to update the route location in AngularJS using $location.path within a function, but I'm encountering some difficulties. app.controller('globalCtrl', function($scope, $route, $location){ $scope.changePath = function(newPat ...

Can using Gulp 4 to import or bundle Bootstrap 5 or Popper.js create a LICENSE.js file?

I am currently working on a project using Gulp 4 and Webpack 5 with Bootstrap 5. During the script bundling process, I have noticed that Gulp generates a bundle.js file as expected, but it also creates a bundle.js.LICENSE.js file. After examining my build ...

Populate a dropdown menu in jQuery with options generated from an array

I'm planning to include 4 dropdowns in my project. My approach involves creating 3 arrays (the first dropdown is hardcoded). The idea is that based on the selection made in the first array, the options for the second dropdown will be populated. How ca ...

rearranging the sequence of buttons using JavaScript

I am faced with the challenge of making a series of buttons draggable and droppable within a parent div without using any external libraries at the request of the client. Although I could have easily accomplished this task with jQuery, it's an opportu ...

Diverse Browser Image Mapping Coordinates

I am in the process of creating an image map, where I specify coordinates on an image that link to other pages. However, I'm encountering an issue where the position of these coordinates is not relative. When viewing the image on a different browser ...

Exploring the functionality of trading-vue library in a simple setup using vanilla HTML and Vue CDN

<html> <head> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a0c0f1f3a48544c544b48">[email protected]</a>/dist/vue.js"></script> ...

The teleport-controls feature is currently not functioning properly in VR mode with Aframe version 0.8.2

Having an issue with the teleport-controls under aframe 0.8.2. When in VR mode using Vive, only the curve appears after touching the trackpad of the controller, but the camera position does not change. However, in flat mode, both the curve and camera posit ...

When state updates in React, the component will rerender without affecting its style

There seems to be a minor oversight on my part. The issue arises in the parent component where I maintain a state of selected items, which are added from the child component. The background color of the child component changes when an item is selected. Ad ...

Encountered a Json Decoder Error when attempting to load data using json.load within Python

I am attempting to read a JSON-formatted text file using the code snippet below with open('orderdata/ETHUSDTorder.txt') as json_file: data = json.load(json_file) actualdata=data['average'] print(actualdata) print("read ...

What strategies would you use to put in place conditional imports in a way that is reminiscent of ReactNative

Is there a way to implement conditional imports in other projects similar to how React Native imports Android or iOS specific classes using *.android.js and *.ios.js? If I wanted to have different classes for development and production purposes, could I u ...

Encountering issues with link button redirection

I have a question regarding a Link element and CustomButton element with an onClick handler. < Link to = "/dashboard" style = { linkStyles } > < CustomButton text = "Login" onClick = { handleSubmit } /> < /Link> The code ...

Setting the initial state with an undo action in React: a step-by-step guide

Is it possible to display a snackbar with an undo action when dragging and dropping events in a react-big-calendar? https://i.stack.imgur.com/QFmYA.png I am trying to implement functionality where clicking on the undo action will revert the event back to ...

The issue of React Js's inline style malfunctioning when using a loop condition

Having some trouble with setting different backgrounds for items in a loop in React JS. I attempted to use inline styles to make it dynamic, but no luck so far. Any tips or solutions? { main.map((item, index) => ( <a key={index} href=&apo ...

Setting an Element's attribute is only visible in the console

Just dipping my toes into the world of Web Development. While playing around with some JavaScript within HTML, I decided to try updating the content of an element. Upon running the code below, "Updated Content" appears in the console as intended. However, ...

If there is a lack of text at the beginning, then insert the

I am currently trying to figure out a solution to automatically add our domain name if it is not included when entering the username. In the code snippet below for my form, I want the script to check if "domainname\" is present before the username. I ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Is there a way for me to know when ng-options has completed updating the DOM?

I am currently working on integrating the jQuery multiselect plugin using a directive within my application. Here is the select element: <select multiple ng-model="data.partyIds" ng-options="party.id as party.name for party in parties ...

Steps for implementing a select all feature with jQuery

I'm currently working on a jQuery function that is acting as a select-all option. Everything is functioning correctly except that when I deselect any of the child elements from select all, the option remains enabled. My goal is to enable or disable th ...

Managing nested Angular repeats with counter

In the previous section of my document, I have a presentation layer that effectively organizes information within a shopping cart. This arrangement functions perfectly fine. At the lower portion, I employ the following code to generate form variables whic ...

jQuery: Eliminating Parent Elements

Currently, I am developing a small web application that allows users to create lists which are then formatted and emailed to them. However, I am facing difficulties in implementing a method that will allow users to delete list items without clearing the en ...