在JavaScript中创建数组时的奇怪行为

时间:2018-11-29 19:23:16

标签: javascript

我有以下代码

 if(ssnFlag == false){
                console.log(userName)
                userSessions.push({userName : [{"sessionId" : dsid}]})
                console.log("pushing::" + JSON.stringify(userSessions[0]))
              }

输出为

OIC_PLAN_ADMIN_OPERATIONS
pushing::{"userName":[{"sessionId":"0000MTEJon9Fs1MLIMK6yf1Ry1Ob0004vf"}]}

请注意,当userName值为OIC_PLAN_ADMIN_OPERATIONS时,为什么在接下来希望像userName这样的单词被推送时,我希望它能推送OIC_PLAN_ADMIN_OPERATIONS

1 个答案:

答案 0 :(得分:3)

您必须添加一些括号以将其变成"Computed property name"

var input = JSON.parse('{"tags":[{"tag":"Peter"},{"tag":"Maria"}],"term":"Jack","type":"name"}');//req;
console.log(input);
var sqlVal = Object
    .entries(input)
    .reduce(function(result, entry) {
        console.log(result,entry);
        const key = entry[0]
        const value = entry[1]
        console.log(key,value);
    if( key === 'term' ) {
    result.push('%' + value + '%')
    } else if( key === 'tags' ) {
        if ( value.length > 1 ) {
            for ( let i=0; i < value.length; i++ ){
                console.log("value is",value);
                result.push('%' + value[i]["tag"]  + '%');//here you are getting object, you should draw the tag value of that object here
            }
        } else {
            result.push('%' + value + '%')
        }
    } else if( key === 'type' ) {
        if ( value.includes(",")  ) {
            var array = value.split(",");
            for ( let i=0; i < array.length; i++ ){
                result.push(array[i])
            }
        } else {
            result.push(value)
        }
    }
    return result
    }, [])

如果省略它们,则与以下内容相同:

  { [userName]: /*...*/ }