1

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.

Flavio Francisco
  • 755
  • 1
  • 8
  • 21
  • 2
    Possible duplicate of [How can I add a key/value pair to a JavaScript object?](https://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object) – TheUnreal Oct 10 '19 at 08:40

3 Answers3

1

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}
});
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
  • keyValue is not a property of my object. `export interface File { [key: string]: any }` since the property has no name how can I set a value to it? – Flavio Francisco Oct 10 '19 at 09:01
1

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 }
Ali Keserwan
  • 217
  • 1
  • 4
0

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.

Flavio Francisco
  • 755
  • 1
  • 8
  • 21