Constructing a key value pair in angular where key value will be given by user

Viewed 55

Construction looks like

l1 = { userid : { key1 : "value1", key2 : "value2"}}

and if userid is set to s5675 I need user id in user place but now output looks like

l1 = {"userid":{"key1":value1,"key2":value2}}

where I need like this

l1 = {"s5675":{"key1":value1,"key2":value2}}

please help me in constructing request like this in angular

2 Answers

Given userid is a variable like

const userid = 's5675';

you can create your desired construct like so

const l1 = {};
l1[userid] = { key1 : "value1", key2 : "value2"};

using anonymous objects defeats the whole purpose of using typescript/angular unless you don't know the internal structure of your object. You should avoid them when possible: Here is a way to strongly type your model using indexable types:

export interface UserEntry {
    [key: string]: UserValues;
}

export interface UserValues {
key1: string;
key2: string;
// ...
}

you can use that in the following manner:

 let userEntries  : UserEntry = {
  "user54": { 
    key1: "this works great with intellisence", 
    key2:"you don't have to guess me"}
 };

console.log(userEntries);
Related