0

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.

3 Answers 3

5

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

1 Comment

We posted almost same answer at same time I would +1 you for great minds thinking alike but I am fresh out of votes today! =]
2

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;
};

Comments

2

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.

1 Comment

Thats cool. I didn't know that! Thanks. Learn something new everyday.

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.