Guerrilla
Guerrilla

Reputation: 14876

Dynamically create object from object array

I have an array of objects that I need to turn into a new single object.

This is structure of array:

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];

I need to turn filters into an object like this:

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

I have been trying with map and assign but I cant figure out the way I am supposed to do this. Does this require reflection of some type or is there a simple way?

Upvotes: 0

Views: 52

Answers (3)

Isaac
Isaac

Reputation: 12874

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

console.log(newObj)

Alternatively you can also use Array#forEach to achieve what you want

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370739

A simple reduce into an object would do it:

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 })
  ), {})
);

Upvotes: 1

31piy
31piy

Reputation: 23859

You can do it using Array#reduce:

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

The idea is to loop over the filters object, and in each iteration, assign the key-value to the result.

Upvotes: 1

Related Questions