0

Ultimately, I want to create an object:

newData = {
    column1: "",
    column2: "",
    column3: "",
    ...
    columnN: ""
}

column names come from another array of objects, which is essentially a global variable tableColumns:

tableColumns = [
    {headerName: "column1", field: "c1", editable: false},
    {headerName: "column2", field: "c2", editable: false},
    {headerName: "column3", field: "c3", editable: false},
    {headerName: "column4", field: "c4", editable: false}
]

Without any hard coding, how can I dynamically create newData via looping through this.tableColumns?

3
  • What will be the value of column1, column2 ... in newData object? Are they empty or null? Commented May 10, 2018 at 6:58
  • @AnkitAgarwal either is ok for me. This newData will be used to insert a new empty row in a table. So I don't care. Commented May 10, 2018 at 7:00
  • Ok I have posted a answer for that. You can set with any value you need Commented May 10, 2018 at 7:03

2 Answers 2

1

Loop over tableColumns and set the value of headerName key as the key of newData object:

var tableColumns = [
    {headerName: "column1", field: "c1", editable: false},
    {headerName: "column2", field: "c2", editable: false},
    {headerName: "column3", field: "c3", editable: false},
    {headerName: "column4", field: "c4", editable: false}
];

var newData = {};

tableColumns.forEach((col)=>{
  newData[col.headerName] = '';
});

console.log(newData);

Sign up to request clarification or add additional context in comments.

1 Comment

@Henrix glad to help
0

Loop through your items and dynamically assign properties based on your headerName column

const tableColumns = [
    {headerName: "column1", field: "c1", editable: false},
    {headerName: "column2", field: "c2", editable: false},
    {headerName: "column3", field: "c3", editable: false},
    {headerName: "column4", field: "c4", editable: false}
];

const result = {};

tableColumns.forEach(item => {
  result[item.headerName] = item.field;
});

console.log(result);

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.