gpt4 book ai didi

javascript - 在 Javascript 中合并共享键上的多个数组

转载 作者:行者123 更新时间:2023-11-28 18:58:15 26 4
gpt4 key购买 nike

我想使用共享 key 将多个数组合并为一个大数组。

我尝试过的:

var conditions = [];
if( aa != undefined )
{
conditions.push( { "query" : { "must" : { "aa" : "this is aa" } } } );
}

if( bb != undefined )
{
conditions.push( { "query" : { "must" : { "bb" : "this is bb" } } } );
}

上面的代码给出:

[
{
"query": {
"must": {
"aa": "this is aa"
}
}
},
{
"query": {
"must": {
"bb": "this is bb"
}
}
}
]

但我需要这个:

[
{
"query": {
"must": [
{
"aa": "this is aa"
},
{
"bb": "this is bb"
}
]
}
}
]

我可以使用 PHP 来完成此操作,但我需要使用 native JavaScript 或使用 underscore.js

最佳答案

定义您推送的对象 - 首先将所有内容推送到内部数组 - 然后将对象推送到外部数组:

var conditions = [];
var query = { query: {} };
if( aa != undefined ) {
if (!query["query"]["must"]) {
query["query"]["must"] = [];
}
//conditions.push( { "query" : { "must" : { "aa" : "this is aa" } } } );
query["query"]["must"].push({ "aa" : "this is aa" });
}

if( bb != undefined ) {
if (!query["query"]["must"]) {
query["query"]["must"] = [];
}
//conditions.push( { "query" : { "must" : { "bb" : "this is bb" } } } );
query["query"]["must"].push({ "bb" : "this is bb" });
}

conditions.push(query);

关于javascript - 在 Javascript 中合并共享键上的多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com