Daniel White
Daniel White

Reputation: 3377

How to iterate through object as key value pair in javascript

I'm creating a Json api in express and node. I have this ALMOST working but I can't figure out how to output the key name in this expression. Here is what I have so far...

for (var k in req.body) {
    if (req.body.hasOwnProperty(k)) {

        if (k != 'formId' && k != 'firstName' && k != 'lastName' && k != 'email' && k != 'phone' && k != 'company' && k != 'subject' && k != 'message') {
            additionalFields.push({
                k: req.body[k]
            });
        }

    }
}

console.log(additionalFields);

And the output is:

[{
    k: '$5000 - $10000'
}, {
    k: ['business cards', 'web design', 'graphicdesign']
}]

Which is ALMOST right, but I want the key's name instead of "k". I'm new to javascript and teaching myself as I go, so this will be a great lesson for me to remember in the future. Here is my desired result, if someone can help me get there, that would be great...

[{
    priceRange: '$5000 - $10000'
}, {
    servicesNeeded: ['business cards', 'web design', 'graphicdesign']
}]

Upvotes: 1

Views: 125

Answers (1)

dfsq
dfsq

Reputation: 193291

For dynamic variable key-names you should use bracket notation. Otherwise key name is interpreted literally as k. Try this:

var obj = {};
obj[k] = req.body[k];
additionalFields.push(obj);

Upvotes: 3

Related Questions