Hella all,
so I am struggling with the following problem:
I have an object with some keys and values. I would like to take them out and make a new array of objects. Here is the code, as it describes my problem better.
const sourceObj = {
test1: "a",
test2: "b",
test3: "c",
test4: "d",
test5: "e"
};
const myTable = [];
for (let value of sourceObj) {
for (let i = 1; i < 6; i++) {
const targetObject = {
foo: "foo",
year: value.test + i,
bar: "bar"
};
myTable.push(targetObject);
}
}
console.log(myTable);
// expected output
// [
// {
// foo: "foo",
// year: "a",
// bar: "bar"
// },
// {
// foo: "foo",
// year: "b",
// bar: "bar"
// },
// ...
// {
// foo: "foo",
// year: "e",
// bar: "bar"
// },
// ]
>Solution :
you can iterate on object keys and use method array.map to get the expected object
const sourceObj = {
test1: "a",
test2: "b",
test3: "c",
test4: "d",
test5: "e"
};
const myTable = Object.keys(sourceObj).map((key) => {
return {
foo: "foo",
year: sourceObj[key],
bar: "bar"
};
});
console.log(myTable);