Parse a map to JSON

0

I am consuming an API from angular, my problem goes when I want is to fill an autocomplete chip data for that I am using angular2-materialize, but according to its structure it should look like this:

autocompleteInit = {
  autocompleteOptions: {
    data: {
      'Apple': null,
      'Microsoft': null,
      'Google': null
    },
    limit: Infinity,
    minLength: 1
  }
};

This would be my angle code: Service:

 getAlltags():Observable<Array<Tag>> {
    return this.http.post<Array<Tag>>(this.url + "list", "");

  }

Component that I want to use the data:

this.tagService.getAlltags().subscribe((tagsParametro) => {
      console.log(tagsParametro)
      this.tags = tagsParametro;
      tagsParametro.forEach(tag => {
        this.map.set(tag.name, null);
      })
      console.log(JSON.stringify([this.map]))
      this.autocompleteInit.autocompleteOptions.data = tagsParametro;
      console.log(this.autocompleteInit.autocompleteOptions)
    }

As you can see I have an Array of "tags" that has attributes name: string, id: number, color: string but I just want the name so I create a map where I just add the names, but I want it to become JSON to be able to use it in angular, like the model specifically "data"

    
asked by liryco 03.08.2018 в 14:53
source

1 answer

0
let array = [ 
  { id: 1,  name: 'Apple', color: 'red' },
  { id: 2,  name: 'Microsoft', color: 'white' },
  { id: 3,  name: 'Google', color: 'blue' } ];

let names = array.map(m => m.name);

let obj: {[k: string]: null} = {};

names.forEach(function (value) {
    obj[value] = null;
}); 

console.log(JSON.stringify(obj));

This prints

{"Apple":null,"Microsoft":null,"Google":null}
    
answered by 03.08.2018 в 15:50