如何从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
queryproperty and merge all its key-value pairs into the result'squeryobject. - Note: If there are duplicate keys across different
queryobjects, 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
相关产品推荐
相关产品推荐

