Skip to main content
  1. About
  2. For Teams
Asked
Viewed 68 times
0

I have the following object

reportData: {}

and the following loop :

    for (var key in ABC.PrintReport.keyList) {
        console.log(ABC.PrintReport.keyList[key].Report_Key);
    }

This loop will print out :

objProperty0
objProperty1
objProperty2
objProperty3

I want to create properties for the object reportData that are named after each ABC.PrintReport.keyList[key].Report_Key.

reportData.objProperty0
reportData.objProperty1
reportData.objProperty2
reportData.objProperty3
1
  • Can you not use bracket notation, like you do with keyList and key? So reportData[objProperty0] = 'something';.
    ajp15243
    –  ajp15243
    2014-03-18 12:59:52 +00:00
    Commented Mar 18, 2014 at 12:59

3 Answers 3

2

You can use square brackets to create properties on objects in JavaScript:

for (var key in ABC.PrintReport.keyList) {
    var k = ABC.PrintReport.keyList[key].Report_Key;
    reportData[k] = 'some value';
}
Sign up to request clarification or add additional context in comments.

Comments

1
for (var key in ABC.PrintReport.keyList) {
    reportData[ABC.PrintReport.keyList[key].Report_Key] = ABC.PrintReport.keyList[key].Report_Key;
}

Comments

1

Something like this should do it (see docs on bracket notation for object property access):

var reportData = {};
for (var key in ABC.PrintReport.keyList) {
    key = ABC.PrintReport.keyList[key].Report_Key;
    reportData[key] = 'some value';
}

1 Comment

This answer is just as good as the one I accepted. The only reason I didn't pick this one is because you overwrite key and it can no longer be used as an index.

Your Answer

Post as a guest

Required, but never shown

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.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.