You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Query对象数组提取数据并创建单个合并对象?

Merge Query Array into a Single Object

To solve this problem, we need to merge the query properties from each object in the input array into a single unified query object. Here are two straightforward approaches to complete your function:

Approach 1: Completing Your For Loop

If you prefer sticking with a for loop, you can initialize an empty result object and iteratively merge each item's query properties into it using Object.assign:

function createQuery(arr) {
  // Start with an empty query container
  const oneQuery = { query: {} };
  
  for (let item of arr) {
    // Merge the current item's query properties into the result
    Object.assign(oneQuery.query, item.query);
  }
  
  return oneQuery;
}

Approach 2: Concise Functional Style with Array.reduce

A cleaner, more idiomatic way is to use Array.reduce, which lets you build the result object in a single pass:

function createQuery(arr) {
  return arr.reduce((acc, item) => {
    // Spread existing query properties and merge with the current item's query
    acc.query = { ...acc.query, ...item.query };
    return acc;
  }, { query: {} }); // Initial empty query object to start with
}

How It Works

  • Both approaches start with a base object { query: {} }.
  • For each element in the input array, we take its query property and merge all its key-value pairs into the result's query object.
  • Note: If there are duplicate keys across different query objects, the last occurrence in the array will overwrite previous ones (this is standard JavaScript object merging behavior).

Example Usage

const queryArr = [ 
  { query: { filter: { term: { search: 'complete' } } } }, 
  { query: { notFilter: { term: { search: 'failed' } } } }, 
  { query: { bool: { term: { search: 'complete' } } } } 
];

const oneQuery = createQuery(queryArr);
console.log(oneQuery);

Output:

{
  query: {
    filter: { term: { search: 'complete' } },
    notFilter: { term: { search: 'failed' } },
    bool: { term: { search: 'complete' } }
  }
}

内容的提问来源于stack exchange,提问作者Etherealm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:11:23