简体   繁体   English

如何将 object 键和值推送到数组

[英]how to push the object keys and values to array

I need to push the key value pair to new array and should build the mongodb $match query.我需要将键值对推送到新数组,并且应该构建 mongodb $match 查询。

const queryFormat = (payload) => {
    delete payload.userEventId
    var query = {}
     var res = []
    for(key in payload) {
        if(typeof(payload[key])) {
       res.push({ [key]: payload[key] })
        }
        else {
            res.push({"$in" :{ [key]: payload[key] }})
        }
    }
    console.log(res[3])
    query['$match'] = {"$and" :res}
    console.log(query)    
}


const payload = {
    id :1,
    name : 'Alfred',
    location : 'moon',
    values : [{name: 'u',age:9}]
}
queryFormat(payload)

expected output预计 output

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u"},{age: 9}]} }]}}

output I got output 我得到了

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u",age: 9}]} }]}}

How to deal with it Thanks!!怎么处理 谢谢!!

Currently you are specifying the key as "key"目前您将密钥指定为"key"

Use [] to specify that you need the value of key as the key使用[]指定需要key的值作为key

 const queryFormat = (payload) => { delete payload.userEventId var query = {} var res = [] for(key in payload) { res.push({ [key]: payload[key] }) } query['$match'] = {"$and":res} console.log(query) } const payload = { id:1, name: 'Alfred', location: 'moon' } queryFormat(payload)

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

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