[英]how to push the object keys and values to array
我需要將鍵值對推送到新數組,並且應該構建 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)
預計 output
{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u"},{age: 9}]} }]}}
output 我得到了
{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u",age: 9}]} }]}}
怎么處理 謝謝!!
目前您將密鑰指定為"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.