从对象数组动态创建对象

时间:2018-07-13 04:51:33

标签: javascript

我有一个对象数组,需要将其变成一个新的单个对象。

这是数组的结构:

class QueryFilter {
    filterName;
    filterValue;
}

let filter1 = new QueryFilter();
filter1.filterName = "SpamScore";
filter1.filterValue = 5;

let filter2 = new QueryFilter();
filter2.filterName = "Pages";
filter2.filterValue = 50;

let filters = [filter1, filter2];

我需要将过滤器变成这样的对象:

let newObj = {
    SpamScore: 5,
    Pages: 50
};

我一直在尝试map和assign,但是我不知道应该怎么做。这需要某种类型的反射还是有一种简单的方法?

3 个答案:

答案 0 :(得分:1)

您可以使用Array#reduce

filters.reduce((r, i) => {
  r[i.filterName] = i.filterValue;
  return r;
}, {});

想法是循环filters对象,并在每次迭代中将键值分配给结果。

答案 1 :(得分:1)

将简单的reduce插入对象即可:

class QueryFilter {
}

let filter1 = new QueryFilter();
filter1.filterName = "SpamScore";
filter1.filterValue = 5;

let filter2 = new QueryFilter();
filter2.filterName = "Pages";
filter2.filterValue = 50;

let filters = [filter1, filter2];

console.log(
  filters.reduce((a, { filterName, filterValue }) => (
    Object.assign(a, { [filterName]: filterValue })
  ), {})
);

答案 2 :(得分:0)

let newObj = {}
    
filters.forEach(x=> {
  newObj[x.filterName] = x.filterValue;
})

console.log(newObj)

或者,您也可以使用Array#forEach来实现所需的目标