Flavio Francisco
Flavio Francisco

Reputation: 775

How can I set a value to an key value pair property in Angular?

Let's say that I have the given object:

export interface File {
  id: string;
  displayname: string;
  filesize: number;
  isarchived: boolean;
  userId: string;
  [key: string]: any;
}

and the following method:

export class BasketService {
    addFile(file: File ) { //Some code here }
}

Than I call my method like this:

this._basketService.addFile({
  id: file.id,
  displayname: file.originalEntry['displayname'],
  filesize: file.originalEntry['filesize'],
  isarchived: file.originalEntry['isarchived'],
  userId: this._appSession.user.id,
  ???: file.originalEntry // <=== How can I set the key value pair here?
});

The object:

file.originalEntry is [key: string]. I would like to pass the entire object instead of individual key/ value pairs.

Upvotes: 1

Views: 2164

Answers (3)

Flavio Francisco
Flavio Francisco

Reputation: 775

I resolved it putting explicitly the key/ value pairs that I needed in my object like this:

const digitalObject = {
        id: file.id,
        displayname: file.originalEntry['displayname'],
        filesize: file.originalEntry['filesize'],
        isarchived: file.originalEntry['isarchived'],
        userId: this._appSession.user.id,
        code: file.originalEntry['code'],
        needle: file.originalEntry['needle'],
        x8: file.originalEntry['x8'][0],
        x5: file.originalEntry['x5'][0],
        8: file.originalEntry['8'][0],
        5: file.originalEntry['5'][0],
        creationtime: file.creationTime
    };

    this._basketService.addFile(digitalObject);

Thanks for the all contributions.

Upvotes: 0

Ali Keserwan
Ali Keserwan

Reputation: 219

if the declaration is like this:

public dictionary: { [key: string]: string } = {};

you can set its value in this way:

this.dictionary = { ID: key, Value: defaultValue }; // key and defaultValue are variables

in your case pass this:

{ ID: key, Value: defaultValue }

Upvotes: 1

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

this._basketService.addFile({
  id: file.id,
  displayname: file.originalEntry['displayname'],
  filesize: file.originalEntry['filesize'],
  isarchived: file.originalEntry['isarchived'],
  userId: this._appSession.user.id,
  keyValue: {key:file.id, value: file.originalEntry}
});

Upvotes: 1

Related Questions