My implementation is like this
interface Data {
[key:string]:string;
}
const array = ["a","b"];
const lines: Data[] = [];
array.forEach((key) => {
lines.push({ key: "some text" });
});
After executing the code, the line array will have entries like [{"key":"some text"}] for example and not [{ "a": "some text"},{ "b": "some text"}]
How can I use value of actual key in building the line objects
>Solution :
It seems like you want to use the elements of the array as keys in your Data objects. To achieve this, you can modify your code like this:
interface Data {
[key: string]: string;
}
const array = ["a", "b"];
const lines: Data[] = [];
array.forEach((key) => {
const line: Data = {}; // Create an empty object for each iteration
line[key] = "some text"; // Use the current key as a property
lines.push(line); // Push the object to the lines array
});
console.log(lines);
In this modified code, we create an empty object line for each iteration of the loop. Then, we set the property with the current key using line[key] = "some text". Finally, we push this object into the lines array.
This way, the resulting lines array will contain objects with keys taken from the array. For example, if array is ["a", "b"], lines will be [{ "a": "some text"}, { "b": "some text"}].