Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use value from forEach in building Record object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"}].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading