我想将多个数组合并为一个带有共享密钥的大数组。
我尝试过的事情:
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做到这一点,但我需要在原生javascript中使用underscore.js
答案 0 :(得分:1)
定义推送的对象 - 首先将所有内容推送到内部数组 - 然后将对象推送到外部数组:
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);
答案 1 :(得分:1)
这不是一件容易的事,因为我看到你想要从最后一个内部属性中创建一个数组。
你推入条件数组的那些对象是否已经存在,或者你自己定义它们?
你可以使用像我这样的递归函数来解决你的问题:
编辑:代码会生成您想要的确切结果。
var object1 = {
query: {
must: {
aa: "this is aa"
}
}
}
var object2 = {
query: {
must: {
bb: "this is bb"
}
}
}
var conditions = {};
function mergeObjects(object, parentObject){
for(var prop in object){
if(parentObject.hasOwnProperty(prop)){
if(typeof parentObject[prop] === "object" && shareProperties(parentObject[prop], object[prop])){
mergeObjects(object[prop], parentObject[prop])
}else{
parentObject[prop] = [parentObject[prop], object[prop]];
}
}else{
parentObject[prop] = object[prop];
}
}
}
function shareProperties(obj1, obj2){
for(var prop in obj1){
if(obj2.hasOwnProperty(prop)){
return true;
}
}
return false;
}
mergeObjects(object1, conditions);
mergeObjects(object2, conditions);
输出:
"{"query":{"must":[{"aa":"this is aa"},{"bb":"this is bb"}]}}"
答案 2 :(得分:1)
对于conditions
的每个后代,检查它是否存在,如果它不存在则创建它。
然后,最后,推送你的新对象:
function addCondition(conditions, key, value) {
conditions[0] = conditions[0] || {};
conditions[0].query = conditions[0].query || {};
conditions[0].query.must = conditions[0].query.must || [];
var o = {};
o[key] = value;
conditions[0].query.must.push( o );
}
var conditions = [];
var aa = 1, bb = 1;
if (typeof(aa) !== 'undefined')
addCondition(conditions, "aa", "this is aa" );
if (typeof(bb) !== 'undefined')
addCondition(conditions, "bb", "this is bb" );
if (typeof(cc) !== 'undefined')
addCondition(conditions, "cc", "this is cc" );
document.getElementById('results').innerHTML = JSON.stringify(conditions, null, 2);

<pre id="results"></pre>
&#13;