0

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?

6
  • Can you post what you've tried? Commented Jul 13, 2018 at 4:51
  • I tried using assign and map and it didn't work so I don't see point of posting it as I am not sure if it is even those methods that I should be using. Commented Jul 13, 2018 at 4:52
  • for(let filter of filters) { newObj[filter.filterName] = filter.filterValue } Commented Jul 13, 2018 at 5:20
  • 1
    It's the same as object.property Commented Jul 13, 2018 at 5:27
  • 1
    more fully: let newObj = {}; for(let f of filters) { newObj[f.filterName] = f.filterValue } Commented Jul 13, 2018 at 5:28

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Ahh thanks. Funnily that method didn't come up when i was googling, thank you very much i will accept when timer allows
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.