简体   繁体   中英

How to map array to new single object in Angular 8?

I'm doing this:

const rawValues = this.filterList.map(s => {
     return {[s.filterLabel]: s.selectedOption}
  });

filterList variable has this type:

export interface SelectFilter {
  filterLabel: string;
  options: Observable<any>;
  selectedOption: string;
}

now rawValues is being mapped like this:

[
{filterLabel: selectedOption},
{filterLabel: selectedOption},
{filterLabel: selectedOption}
]

so it's an array of my new objects,

but what I want is a SINGLE object, so the end result should be:

{
filterLabel: selectedOption,
filterLabel: selectedOption,
filterLabel: selectedOption
}

NOTE that " filterLabel " will always be unique.

What do I need to change in the map() ?

For this use case, a map isn't needed as it would result in creating a new array which is unnecessary. Just iterate over each element in the array then assign each filterLabel as a new key to the obj like this:

const obj = {};
this.filterList.forEach(s => {
  obj[s.filterLabel] = s.selectedOption;
});

console.log(obj);

I think this is use case for array reduce:

 let result = [{filterLabel: 'label1', selectedOption: 'option1'}, {filterLabel: 'label2', selectedOption: 'option2'}, {filterLabel: 'label3', selectedOption: 'option3'}, {filterLabel: 'label4', selectedOption: 'option4'} ].reduce(function(previousValue, currentValue, index, array) { return { [currentValue.filterLabel]: currentValue.selectedOption, ...previousValue } }, {}); console.log(result);

More details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

You shouldn't do anything to get the result you want. First, when you run a map on the array, a new array is returned. To change that you would have to re-write the map function with your own. Technically possible, but not recommended.

Second, you cannot have multiple properties on an object that have the exact same name. I know of no way around this.

You might be able to do something like what you want with a loop:

let rawValues = {};
for (i = 0; i < filterList.length; i++) { 
  rawValues[`${filterList[i].filterLabel}${i}`] =  filterList[i].selectedOption;
}

Which should give you something like this:

{
   filterLabel1: selectedOption,
   filterLabel2: selectedOption,
   filterLabel3: selectedOption
}

Can you guarantee that the filterLabel will always be unique?

var result = {};
this.filterList.forEach(s => {
  result[s.filterLabel] = s.selectedOption;
});

you can use reduce to achieve the same result:

var result = this.filterList.reduce((prev, next) => {
  return {...prev, [next.filterLabel]:next.selectedOption}
}, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM