Amanda
Amanda

Reputation: 175

For loop not using argument from JavaScript function

I'm trying to run this function in my server.js file:

function formatArr (targetArr, characteristic, formattedArr) {
    console.log(characteristic);
    for (var i = 0; i < targetArr.length; i++) {
        formattedArr.push({characteristic:targetArr[i]})
    };
    return formattedArr;
};

If I call it like so:

var targetSize = Object.keys(JSON.parse(req.query.size)); //[s,m,l]
var sizeKey = "size";
// format size array for mongodb query 
var formattedSize = [];
var formattedSize = formatArr(targetSize, sizeKey, formattedSize);
console.log(formattedSize);

it DOES console log "size", but it does NOT replace the word characteristic with the word size in the formattedSize array. Here's what I get in my server console:

size
[ { characteristic: 's' },{ characteristic: 'm' },{ characteristic: 'l' } ]

How do I make it replace characteristic with size within the array? This is my desired output:

size
[ { size: 's' },{ size: 'm' },{ size: 'l' } ]

I want to be able to reuse the formatArr function with other characteristics.

Upvotes: 0

Views: 40

Answers (3)

Pointy
Pointy

Reputation: 413767

In very new JavaScript environments, you can write:

    formattedArr.push({ [characteristic]: targetArr[i] })

Otherwise, you'll have to build an object step-by-step as in @dfsq's answer.

Upvotes: 2

AtheistP3ace
AtheistP3ace

Reputation: 9691

Try this:

function formatArr (targetArr, characteristic, formattedArr) {
    for (var i = 0; i < targetArr.length; i++) {
        var obj = {};
        obj[characteristic:targetArr] = targetArr[i]
        formattedArr.push(obj)
    };
    return formattedArr;
};

Upvotes: 2

dfsq
dfsq

Reputation: 193281

You should use bracket notation for variable property names:

function formatArr (targetArr, characteristic, formattedArr) {
    console.log(characteristic);
    for (var i = 0; i < targetArr.length; i++) {
        var obj = {};
        obj[characteristic] = targetArr[i];
        formattedArr.push(obj);
    };
    return formattedArr;
};

A little verbose but still. If you are in ES2015 friendly environment you can use shorter syntax:

for (var i = 0; i < targetArr.length; i++) {
    formattedArr.push({[characteristic]: targetArr[i]});
};

Upvotes: 5

Related Questions