繁体   English   中英

试图将数组作为键值对放入对象中。 没有得到想要的 output?

[英]Trying to put array as an key-value pair in objects. Not getting desired output?

我创建了一个插入 function。

insert(obj4, ["whisky", "balentine"], ["pasta", "pesto"]);

obj4 是我打算将那些 arrays 对作为键值对放入的项目。 每个数组中的第一项将作为键,第二项作为值对。 我正在尝试 output 我的临时 object 我只得到 [object object]。 我现在该怎么办? 代码是否正确?

我创建了这个 function:-

function insert(obj, ...pairs){

    //Holds the objects temporarily
    var tempObj = {}; 

    for(let i = 1; i < arguments.length; i++){
        if(arguments[i].length > 2){
            console.log("Too long")
            return;
        } else {
            tempObj[arguments[i][0]] = arguments[i][1];
        }
    }

    //Trying to log my temp object 
    console.log("Test " + tempObj);
}

insert(obj4, ["whisky", "balentine"], ["pasta", "pesto"]);

补充一下 vipul patel 所说的,如果你想控制字符串 Test 和 object 你可以这样做, console.log('Test', tempObj);

您正在尝试使用字符串连接打印 object。 所以它使用toString打印[object object]。 你的代码是正确的。 只需打印 object 就可以看到实际的 Object

 function insert(obj, ...pairs){ //Holds the objects temporarily var tempObj = {}; for(let i = 1; i < arguments.length; i++){ if(arguments[i].length > 2){ console.log("Too long") return; } else { tempObj[arguments[i][0]] = arguments[i][1]; } } //Trying to log my temp object console.log(tempObj); } insert({}, ["whisky", "balentine"], ["pasta", "pesto"]);

您也可以使用reduce

 function insert(obj, ...pairs){ if(pairs.length > 0){ var result = pairs.reduce(function(accumalator, currentValue){ accumalator[currentValue[0]] = currentValue[1]; return accumalator; }, obj); return result; }else{ return obj; } } var obj4 = {"ice":"cream"}; var result = insert(obj4, ["whisky", "balentine"], ["pasta", "pesto"]); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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