I want to generate JSON data in an array to pass to another component. For this, I followed a method as follows. But I guess I wasn't very good. I'm new to this business and trying to learn.
employeeMoney: any[] = [];
employeeId: any[] = [];
this.employeeMoney.push(event.target.value);
this.employeeId.push(employId);
This is how I throw the data I get from the user with the input. I'm pushing data into this array I created in the same function.
this.employeeMoney.map(function(item) {
blopp.all.money.push(item);
});
this.employeeId.map(function(item) {
blopp.all.id.push(item);
});
let blopp: any = {
all: [{id: '', money:''}]
};
My goal here is to collect data from 2 different array lists into a single list. Then I want to generate the JSON data in the format I want using the data I have collected in this single list. But here I am encountering an error. when you enter the data in the input. This error pops up in the console.
ERROR ReferenceError: Cannot access 'blopp' before initialization
i couldn't solve this error. I'm trying to create such a JSON structure using the latest money and id data.
blopp.map(function(item: any) {
blopp.money.push({
"employee_id" : '',
"amount" : item,
"currency" : 'USD'
})
});
But I have a question here, how can I print 2 different data in the same array list to the same JSON structure.
CodePudding user response:
Assuming that both employeeMoney
and employeeId
will always have the same order and length as to if they were connected somehow. here is one possible solution.
const length = employeeId.length;
for (let index = 0; index < length; index ) {
blopp.all.push({id: employeeId[index], money: employeeMoney[index]})
}
But as a side note, I don't know what exactly are you doing, but I have got a bad feeling about it. Maybe you have some issues with your system design?
CodePudding user response:
First of all you have to fix the types since you declare them string and put data structures in them.
Secondly you cannot push directly on array property just like you are doing on: blopp.all.money.push(item);
Here is the answer, since blopp is an object which contains an array of objects of type {id: '', money: ''}
when you push you should do the following:
blopp.all.push({id: 1, money: '1000'})