0

I have an empty JSON object

export class Car {}

I have imported it in a component.ts and I would like to add some fields in a loop. Something like

aux = new Car;
for (var i = 0; i < 10; i++) {
 car.addName("name" + i);
}

My goal would be to get at the end the following object

car: {
  name1: name1;
  name2: name2;
  ....
}

I have created the JSON object empty because at the beginning I do not know how many elements or fields will have. I could create this object by javascript. I do not need to have an export class

is it possible?

5
  • 2
    Cant use the same key twice in an object, could have an array of objects tho... Commented Mar 21, 2018 at 16:25
  • sorry, typo. I m gonna update it Commented Mar 21, 2018 at 16:26
  • What is the relationship between Car and ImportParameter? You're not using the second one at all in your component Commented Mar 21, 2018 at 16:42
  • What is car? What is aux? Are they properties of ImportParameter class? Commented Mar 21, 2018 at 17:11
  • Sorry. That was also a typo Commented Mar 21, 2018 at 17:19

3 Answers 3

1

You can simply add properties like this

aux = new Car;

for (var i = 0; i < 10; i++) 
{
  aux["name" + i] = "name"+i;
}
Sign up to request clarification or add additional context in comments.

Comments

1

I could create this object by javascript. I do not need to have an export class

Yes it is possible.

Working Demo

var car = {};

for (var i = 0; i < 10; i++) {
 car["name" + (i+1)] = "name" + (i+1);
}

console.log(car);

Comments

1

Why do you define a class for an empty object? In any case, define an interface:

export interface Car {
     [id: string]: string
}

Now, to fill it:

const car = <Car>{};

for (var i = 0; i < 10; i++) {
    car[`name${i}`] = `name${i}`;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.