Updating Key-Value pairs in an ArrayList using Angular 4

After importing json data into an arrayList and storing it in local-storage, the structure looks like this:

[
    {
        "id": 1,
        "name": "Albany",
        "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
        "price": 15.49,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgA..."
    },
    {
        "id": 2,
        "name": "Blue Ribbon",
        "manufacture": "Blue Ribbon Brown Plus Low Gi Bread 700g",
        "price": 13.99,
        "category": "Food",
        "type": "Breads",
        "image": "data:image/octet-stream;base64,/9j/4AAQSkZJRgABA..."
    },
    {...},
    {...},
    ...
]

The next step involved creating a class that extracts these values from local storage, filters them based on a specific product type, and modifies the information accordingly. Here's how the class is structured:

export class MilkCreamComponent implements OnInit {

  allProducts: Array<Product> = [];
  quantity: number = 1;
  resultArray:any;
  milkProducts =[]
  newMilkProducts = [];

  constructor( private prod: ProductService, public _DomSanitizer: DomSanitizer) { }

  ngOnInit() {

    this.allProducts = JSON.parse(localStorage.getItem('product-data') );

    var productMilk = this.allProducts.filter(item => item.type === 'Milk');
    this.milkProducts = productMilk;

      for (var i=0; i < this.milkProducts.length / 4; i++) {
        var imageString = this.milkProducts[i].image;
        var edittedImageString = imageString.substring(imageString.indexOf(",") + 1 );
        var newImageStringFormat = "data:image/jpeg;base64," + edittedImageString;

        if ( edittedImageString ===  this.milkProducts[i].image.substring(this.milkProducts[i].image.indexOf(",") + 1) ){

          var index = this.milkProducts.indexOf( this.milkProducts[i] );

          if (index !== -1) {
            this.milkProducts.indexOf[index] =  this.milkProducts[i].id, this.milkProducts[i].name, this.milkProducts[i].manufacture,
                                this.milkProducts[i].price, this.milkProducts[i].category, this.milkProducts[i].type, newImageStringFormat;
            console.log (  this.milkProducts );
            }
        }
        else{
          console.log("Images Are Not Equal\nSee milk-cream.component.ts\nSee Image Conversion Codes");
        }
      }

  }
}

interface Product {
  id: number;
  name: string;
  manufacture: string;
  price: number;
  category: string;
  type: string;
  image: string;
}

The main objective now is to update specific key values within the array list and then display the modified arrayList through console log.

Answer №1

Give this a shot:

this.allItems = JSON.parse(localStorage.getItem('item-data'));

this.allItems.forEach(function(product) {
  if (product.category === "Cookies") {
    var newImageString = product.pic.substring(product.pic.indexOf(",") + 1 );
    product.pic = "data:image/png;base64," + newImageString;
  }
});

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

Experiencing a result of NaN following a mathematical operation on variables

While working with an array obtained from a JSON response, I am encountering NaN after performing addition operations. var a = new Array(); var b = 0; var c = 0; alert(b); for (var x = 0; x < length; x++) { a[x] = response.data[x] } for (var i = 0; ...

What is the best way to specify a blank email field in JSON data?

Creating a JSON schema for email addresses that accepts either an empty value or a properly formatted email. This is the approach I have used: "emailID": { "type": "string", "required": false, ...

Filtering arrays using JSONPath

I'm currently grappling with JSON paths and encountering a particular problem. Unfortunately, I am unable to display the exact original file I am dealing with, but I have replicated the issue using this simplified JSON: { "store": { "book" ...

The challenge of parsing nested JSON data with ReactJS and Sockets

My JSON file named "data.json" has the following structure: { "Object1": { "name": "1", "rank": "2" }, "Object2": { "name": "3", "rank": "4" } } In my React code, I am setting the state using this data. I w ...

What are the steps to configure JSS in a TypeScript/NextJS application?

Trying to set up a basic web app using React, TypeScript, NextJS, and Material-UI has been quite the challenge. The main issue I am facing revolves around styling within my project. To better illustrate my problem, I have created a CodeSandbox environment. ...

Discover the secrets to dynamically swapping out all columns in a Data Table with Angular2+

Whenever changes or events occur outside of the Data Table, my requirement is to replace all the columns. When the data table is displayed for the first time, it shows selected columns based on an event. However, if I select another option, the new column ...

What is the best way to forward specific props from a parent to its children?

Currently, I am working on a React + Typescript architecture called "forward." The purpose of this architecture is to pass all props received down to its children components. However, I have encountered an issue where I want to restrict the type of props ...

Modifying the value of a property in an object array created using the map method is ineffective

I have a collection of objects: https://i.sstatic.net/XNrcU.png Within the collection, I wished to include an additional property to the objects. To achieve this, I utilized the map function: returnArray = returnArray.map((obj) => { obj.active = "fal ...

Utilizing Spring and JPA to Store Data in a JSON Column within a Postgres Database

My database table "test" in Postgres 9.3 has a column named "sample_column" of type json that I'm trying to populate with {"name":"Updated name"} using Spring / JPA. After researching, I found that I need to implement a custom converter to map the st ...

Tips for utilizing state and city dropdown menus in JavaScript multiple times without interfering with other dropdowns

Currently, I am utilizing CodeIgniter to create a dynamic dropdown functionality. The setup involves four select country dropdowns where the state options will populate based on the selected country, and once a state is chosen, the corresponding city optio ...

How can dependencies for an entire class or module be mocked in the mocha ecosystem similar to jest.mock?

I am currently working on unit testing a module that resembles the following code structure: import { Countdown } from "./database/orm"; export class PersistentTimer { protected constructor(...) { ... } // To ensure database writing ...

Ways to activate a function when the active tab in mat-tab is clicked

I am currently using angular 6 and I have set up a tab system with 3 tabs, each calling a different component. <mat-tab label="one"> <score-football ></ score-football > </mat-tab> <mat-tab label="second"> <score-hockey & ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

QueryFailedError: Null values found in the "price" column - TypeORM - PostgreSQL

I have developed a straightforward table: import { Column, Entity, PrimaryGeneratedColumn } from "typeorm" @Entity() export class Test { @PrimaryGeneratedColumn() public id!: number @Column({ nullable: false }) public name!: string @ ...

What is the reason behind permitting void functions in the left part of an assignment in Typescript?

Take a look at this Typescript snippet: let action = function (): void { //perform actions }; let result = action(); What makes it suitable for the TypeScript compiler? ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

What is the best way to switch to a different screen in a React Native application?

I've recently dived into the world of React Native and embarked on a new project. The initial screen that greets users upon launching the app is the "welcome screen," complete with a prominent 'continue' button. Ideally, clicking this button ...

Refresh Layers in Openlayers with LayerRedraw(), Rotate Features, and Manipulate Linestring Coordinates

TLDR: I am facing difficulties with my OpenLayers map. Specifically, I want to remove and add a layer called 'track', or find a way to plot a triangle based on one set of coordinates and a heading (see below). In my OpenLayers map, there is an i ...

Creating a declaration file for a library's entry point involves outlining the structure and types

I have developed an npm library that is made up of several ES6 modules, which are then consolidated into a single js file. The directory structure looks like this: src main.ts one.ts two.ts three.ts types index.d.ts index.ts The index.ts fil ...

How can I access the ng-template in a component?

How can I reference <ng-template #modal_Template> in my component.ts file? Previously, I triggered a modal using a button on my HTML file and included this code: <button type="button" class="btn btn-primary" (click)="openModal(modal_Template)"> ...