Is there a way to create identical copies of data with the identical names?

Here is the code I have written:

this.temp1.push(this.json);

for(let i=0; i<this.temp1.length; i++){
    if(this.temp1[i].name == this.json.name){       
        this.orderList[i] = this.json;
        this.DBorder[i] = this.order_json;      
    }
    else{
        this.orderList.push(this.json);
        this.DBorder.push(this.order_json);
    }
}

This is my first input data:

[{"name":"Pad-Thai", "price":10,"amount":1,"total":10}]

Here is my second input data, now with a new amount included:

[{"name":"Pad-Thai", "price":10,"amount":3,"total":30}]

The current result of the process is as follows:

[{"name":"Pad-Thai", "price":10,"amount":3,"total":30},
{"name":"Pad-Thai", "price":10,"amount":3,"total":30}]

However, the expected result should be:

[{"name":"Pad-Thai", "price":10,"amount":3,"total":30}]

Answer №1

  1. Verify the name and make updates if it already exists, otherwise add a new object to the array.

        const obj1 = { "name": "Pad-Thai", "price": 10, "amount": 1, "total": 10 };
            const obj2 = { "name": "Pad-Thai", "price": 10, "amount": 3, "total": 30 };
            const obj3 = { "name": "Some-Other-Dish", "price": 20, "amount": 2, "total": 40 };
    
            let temp1 = [];
            function addItem(obj) {
                let index = temp1.findIndex(x => x.name === obj.name);
                if (index > -1) {
                    temp1[index] = obj;
                } else {
                    temp1.push(obj);
                }
            }
            addItem(obj1);
            addItem(obj2);
            addItem(obj3);
            console.log('temp1 : ', temp1);

  2. If an object with the same name has already been added, you can remove it using a for loop and finding its index or by reducing the loop.

        const output = [
            { "name": "Pad-Thai", "price": 10, "amount": 1, "total": 10 },
            { "name": "Pad-Thai", "price": 10, "amount": 3, "total": 30 },
            { "name": "Some-Other-Dish", "price": 20, "amount": 2, "total": 40 }
        ]
    
        let temp1 = [];
        output.forEach(obj => {
            let index = temp1.findIndex(x => x.name === obj.name);
            if (index > -1) {
                temp1[index] = obj;
            } else {
                temp1.push(obj);
            } 
        });
        console.log('temp1 : ', temp1);

Answer №2

const data1 = [{
  "name": "Sushi",
  "price": 15,
  "amount": 2,
  "total": 30
}]
const data2 = [{
  "name": "Sushi",
  "price": 15,
  "amount": 2,
  "total": 60
}];

function combine(existing, updated, identifier) {
  const mappedData = updated.reduce((accumulator, element) => {
    return { ...accumulator,
      [element[identifier]]: element
    };
  }, {});

  return existing.map(element => {
    const modified = { ...element,
      ...mappedData[element[identifier]]
    };

    delete mappedData[element[identifier]];

    return modified;
  }).concat(Object.values(mappedData));
}

console.log(combine(data1, data2, "name"));

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

Definitions for TypeScript related to the restivus.d.ts file

If you're looking for the TypeScript definition I mentioned, you can find it here. I've been working with a Meteor package called restivus. When using it, you simply instantiate the constructor like this: var Api = new Restivus({ useDefaultA ...

Angular 2 RC 5 is facing an unhandled promise rejection issue that needs

Since updating my angular2 to rc5, I encountered an error when trying to load my app: zone.js:461 Unhandled Promise rejection: Error: DI Exception at NoProviderError.BaseException [as constructor] (http://localhost:4200/vendor/@angular/core/src/fa ...

The panning functionality on Android devices within the Firefox browser is currently experiencing issues with both panstart and pan

Currently, I am collaborating on an Angular7 project and utilizing hammerjs version 2.0.1. One of the tasks at hand is to allow panning functionality on a map for mobile devices. After testing on various android devices, I noticed that it performs well on ...

What are some techniques to encourage a grandchild to utilize the grandparent <router-outlet> within Angular 6?

This link will take you to a Stack Blitz demo that illustrates what I'm trying to achieve: https://angular-czk5vj.stackblitz.io/ In essence, my goal is to have the grand child route render within the grand parent router-outlet. Example: Routes: Emp ...

What are the steps to resolve TypeScript errors in OpenLayers version 6.6.1?

Since updating to OpenLayers 6.6.1, I have been bombarded with numerous typescript errors related to generics. For example... import olLayerVector from 'ol/layer/Vector'; import olFeature from 'ol/Feature'; public static highlightOver ...

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

Facing issues with integrating Mixpanel with NestJS as the tracking function cannot be located

While utilizing mixpanel node (yarn add mixpanel) in conjunction with NestJS, I have encountered an issue where only the init function is recognized. Despite calling this function, I am unable to invoke the track function and receive the error message: Ty ...

Ways to assign unpredictable values (such as ids, dates, or random numbers) to a Domain Entity or Aggregate Root when it has been injected as dependencies

I am currently developing a frontend repository that follows an innovative hexagonal architecture approach with domain-driven design principles, and it utilizes Redux Toolkit. The development process involves Test-Driven Development (TDD) where I employ c ...

Remove the main project from the list of projects to be linted in

Currently in the process of transitioning my Angular application to NX and have successfully created some libraries. I am now looking to execute the nx affected command, such as nx affected:lint, but it is throwing an error: nx run Keira3:lint Oops! Somet ...

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

Comparing TypeScript's `return;` with `return undefined;`: which is better?

I encountered a strange behavior that is puzzling to me, and I'm not sure if there's a logical explanation for it. In TypeScript, the following code works perfectly: type UndefinedFunction = () => undefined; let uf: UndefinedFunction = funct ...

How can a singleton object be referenced or injected into a constant in Angular?

I have experience implementing dependency injection in a component class. For example: constructor(private staticDataService: StaticDataService) But I am curious if it's possible in Angular 7 to inject the singleton staticDataService object as an at ...

Ways to retrieve the initial 4 elements from an array or class organized by their price entries in ascending order

Let's say we have an array of objects representing products: Products: Product[] = [ { id: 1, name: 'Milk', price: '1' }, { id: 2, name: 'Flour', price: '20' }, { id: 3, name: 'Jeans', pri ...

Struggling to access component variables within the setTimeout function

As a newcomer to Angular(6), I am facing an issue where I am unable to access component variables within a setTimeout function. Below is the code snippet illustrating my problem. export class ConSellerDraftsolSecOneComponent implements OnInit { ...

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. https://i.sstatic.net ...

What is the best way to display a Nested JSON structure without an object key?

Need help with extracting data from two different JSON structures. The first one is straightforward, but the second is nested in multiple arrays. How can I access the content? See below for the code snippets: // First JSON { "allSuSa": [ { ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

Having issues transferring files from Angular 8 to NodeJS

After successfully implementing a component for drag and drop file functionality using Angular, I encountered an issue when trying to create a service for server requests. The DragDropDirective is as follows: // Code for DragDropDirective import { Direct ...

Guide on incorporating a library into your Ionic application without the need to upload it to npm

Recently, I successfully created an Angular application, an Ionic application, and a custom library in my workspace. I am able to import the library files into my Angular application but facing challenges when trying to import them into my Ionic applicat ...

HTML set hover & active states to remain active indefinitely

NOTE: My project utilizes Angular, so Angular may offer a solution to this issue as well I am in the process of creating a page where I can preview and test out various styles that I have designed. In order to achieve this, I need to somehow activate both ...