0

I would like to filter my data depending on a typed keyword.

https://jsfiddle.net/LeoCoco/e96L8akn/

let keyword = '-pre';

let data = {
  'Basic': [{
    name: 'a-basic'
  }, {
    name: 'b-basic'
  }, {
    name: 'c-basic'
  }],
  'Premium': [{
    name: 'a-pre'
  }, {
    name: 'b-pre'
  }, {
    name: 'c-pre'
  }],
  'Extra': [{
    name: 'a-ext'
  }, {
    name: 'b-ext'
  }, {
    name: 'c-ext'
  }],
};

Output

'Premium': [{name: 'a-pre'}, { name: 'b-pre'}, { name: 'c-pre'}]

My try

lodash.forEach(data, (card) => {
  card = card.filter(o => {
    return Object.keys(o).some(k => {
      return typeof o[k] === 'string' && o[k].toLowerCase().includes(keyword.toLowerCase());
    });
  });
})

But it does not work.The difficulty for me is that the filtering must happen on the nested object keys contained in each array.

1
  • card is lost. Do sth like data[card]=card.filter Commented Jun 23, 2017 at 15:37

2 Answers 2

1
 var result={};
 Object.keys(data).forEach(key => {
   result[key] = data[key].filter(o => {
       return Object.keys(o).some(k =>typeof o[k] === 'string' && o[k].toLowerCase().includes(keyword.toLowerCase()));
  });
})
Sign up to request clarification or add additional context in comments.

1 Comment

superfluous curly brackets and return statements in arrow functions, no explanations.
1

Because this is object you can use reduce() on Object.keys() instead and then inside use every() to check for keyword.

let keyword = '-pre';

let data = {"Basic":[{"name":"a-basic"},{"name":"b-basic"},{"name":"c-basic"}],"Premium":[{"name":"a-pre"},{"name":"b-pre"},{"name":"c-pre"}],"Extra":[{"name":"a-ext"},{"name":"b-ext"},{"name":"c-ext"}]}

var result = Object.keys(data).reduce(function(r, e) {
  var check = data[e].every(o => o.name.indexOf(keyword) != -1);
  if(check) r[e] = data[e]
  return r;
}, {})

console.log(result)

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.