1
votes

I'm trying some features of Angular. I'm facing a problem with Object and Array. Let's say I've a custom component, Filter, and a service, FilterService. Here's my code:

filter.component.ts

import { Component, OnInit } from '@angular/core';
import { FilterService } from '../services/sinsense-filter.service';

@Component({
    ...
})

export class FilterComponent implements OnInit {

  public appliedFilters: string[] = []

  constructor(public filterService: SisenseFilterService) {}

  ngOnInit() {
    var obj = this.filterService.filtersApplied;

    var result = Object.keys(obj).map(function (key) { 
        return [Number(key), obj[key]];
        // return [obj[key];
    }); 

    // this.appliedFilters=result;
    // console.log(this.appliedFilters);
    // console.log(typeof(result));

  }
}

Note: I've commented out the solutions that I tried

and here's the service code filter-service.ts

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class FilterService {
    filtersApplied: object;
    constructor() {
        this.filtersApplied = new Object();
        
        this.filtersApplied={
            property1: "value1",
            property2: "value2",
            property3: "value3"
        }
    }
}

I'm following an article on GeeksForGeeks: How to convert an Object {} to an Array [] of key-value pairs in JavaScript?

but I'm getting compatibility error:

Type 'any[][]' is not assignable to type 'string[]'.

Type 'any[]' is not assignable to type 'string'.

Please correct me. I don't want keys in my final array. I just want appliedFilters to be:

["value1", "value2", "value3"]

1

1 Answers

2
votes

.map operator takes the function which should return the value made from each element in the given array in order to create new array of the same length. So in your code you need to return just the desired value via obj[key] instead of returning unnecessary array for each item.

....
var result = Object.keys(obj).map(function (key) { 
    return obj[key] // return just the value!
});