1

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']
}]

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Your (now deleted) comment is confusing because it sounds like you're saying that your answer is syntactically incorrect.
Thank you @Robert. I was commenting on another OP's comment, where they assumed one more incorrect version.

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.