简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM