我想从一个对象数组中创建一个对象。请参阅提供的代码。
这是输入数组
let queryArr = [
{
query: {
filter: {
term: {
search: 'complete',
}
}
}
},
{
query: {
notFilter: {
term: {
search: 'failed',
}
}
}
},
{
query: {
bool: {
term: {
search: 'complete',
}
}
}
}
]
预期输出
let oneQuery = {query: {
bool: { ... },
filter: { ... },
notFilter: { ... } // data from respective array object key
}};
我写的功能
function createQuery(arr){
for(let i = 0; i < arr.length; i++){
if(Object.keys(arr[i].query === 'bool')){
oneQuery.query.bool = arr[i].query.bool;
}
if(Object.keys(arr[i].query === 'filter')){
oneQuery.query.filter = arr[i].query.filter;
}
if(Object.keys(arr[i].query === 'notFilter')){
oneQuery.query.notFilter = arr[i].query.notFilter;
}
}
return oneQuery;
}
createQuery(queryArr);
我得到的输出:
query: {
bool: { ... },
filter: undefined,
notFilter: undefined
}
我不知道我在这里做错了什么。使用reduce或map的解决方案将是首选。
答案 0 :(得分:5)
使用Array.map()
获取包含每个query
属性内容的数组,然后spread进入Object.assign()
以合并为一个对象:
const queryArr = [{"query":{"filter":{"term":{"search":"complete"}}}},{"query":{"notFilter":{"term":{"search":"failed"}}}},{"query":{"bool":{"term":{"search":"complete"}}}}];
const createQuery = (arr) => ({
query: Object.assign({}, ...queryArr.map(({ query }) => query))
});
console.log(createQuery(queryArr));
&#13;
要修复代码,请初始化查询项,然后从数组中的每个项中获取第一个键 - arr[i].query)[0]
:
const queryArr = [{"query":{"filter":{"term":{"search":"complete"}}}},{"query":{"notFilter":{"term":{"search":"failed"}}}},{"query":{"bool":{"term":{"search":"complete"}}}}]
function createQuery(arr){
const oneQuery = { query: {} };
for(let i = 0; i < arr.length; i++){
if(Object.keys(arr[i].query)[0] === 'bool'){
oneQuery.query.bool = arr[i].query.bool;
}
if(Object.keys(arr[i].query)[0] === 'filter'){
oneQuery.query.filter = arr[i].query.filter;
}
if(Object.keys(arr[i].query)[0] === 'notFilter'){
oneQuery.query.notFilter = arr[i].query.notFilter;
}
}
return oneQuery;
}
console.log(createQuery(queryArr));
&#13;
答案 1 :(得分:1)
你的问题似乎是这一行
Object.keys(arr[i].query === 'filter')
此评估结果为Object.keys(true)
或Object.keys(false)
使用reduce
queryArr.reduce( (acc, c) => (
acc[ Object.keys(c.query)[0] ] = Object.values(c.query)[0], //set the first key and value to accumulator
acc ), //return the accumulator
{}); //initialize accumulator to {}