1

My code is as follows :

let filters = [ 
    {name: "MAKE", values: 
    [
      {
        Volkswagen: {active: true, make: "Volkswagen"},
        Skoda: {active: true, make: "Skoda"}
      }
    ]
    }
]

function getFilterValues(){
  return filters.filter(f => {
    if(f.name == "MAKE"){
      return f.values.filter(i => {
        Object.keys(i).map(key => {
          return key;
        });
      });
    }
  });
}

var div = document.getElementById('output');
div.innerHTML = getFilterValues();

I want to loop through filters to get the object keys.

Thus the result that I want is, in this case Volkswagen, Skoda. But my function getFilterValues doesn't return what I want.

Here is jsfiddle.

Any advice?

6
  • The map s don't really do anything, and you don't return anything in the filter ? Commented Sep 12, 2016 at 7:22
  • You did not understand how base array function works, how anybody can help to you? Commented Sep 12, 2016 at 7:23
  • 2
    i suggest to change the data structure to a more itarable style, without object/key parts. Commented Sep 12, 2016 at 7:24
  • 2
    jsfiddle.net/o93Lm0rc/103 Commented Sep 12, 2016 at 7:25
  • @adeneo, i miss the data to filter ... Commented Sep 12, 2016 at 7:26

2 Answers 2

1

The main problem is with the filter function. You want map since with filter you return true/false whether the element should be included in the resulting code. Check out this diff: https://www.diffchecker.com/CX6hOoxo

This works: https://jsfiddle.net/o93Lm0rc/101/

let filters = [ 
    {name: "MAKE", values: 
    [
        {
            Volkswagen: {active: true, make: "Volkswagen"},
            Skoda: {active: true, make: "Skoda"}
        }
    ]
    }
]

function getFilterValues(){
    return filters.map(f => {
        if(f.name == "MAKE"){
            return f.values.map(i => {
                return Object.keys(i).map(key => {
                    return key;
                });
            });
        }
    });
}


var div = document.getElementById('output');

div.innerHTML = getFilterValues();
Sign up to request clarification or add additional context in comments.

1 Comment

Of course. I forgot to return the key. But @adeneo solution is much cleaner. Thanks.
1

You can use Object.keys() to get the list of keys.

var filters = [{
  name: "MAKE",
  values: [{
    Volkswagen: {
      active: true,
      make: "Volkswagen"
    },
    Skoda: {
      active: true,
      make: "Skoda"
    }
  }]
}];

for (i = 0; i < filters.length; i++) {
  if (typeof filters[i].values == "object") {
    console.log(Object.keys(filters[i].values[0]));
  }
}

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.