Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Filter Non-Array JSON Object

I am trying to filter non-array JSON object as the following snippet

const filter = { filterRows: ['one'] };

const templateMapper = {
  'one': {
    title: 'one',
  },
  'two': {
    title: 'two',
  },
  'three': {
    title: 'three',
  },
}

const filterDialogView = filter.filterRows;
const filterTemplateMapper = [templateMapper].filter(row => !filterDialogView.includes(row));
console.log(filterTemplateMapper);

But it's not filtering

I am getting following output

[
  {
    "one": {
    "title": "one"
  },
  "two": {
    "title": "two"
  },
  "three": {
    "title": "three"
  }
 }
]

Desire output

 {
  "two": {
    "title": "two"
  },
  "three": {
    "title": "three"
  }
 }

I want to filter row based on filterRows for example if filterRows contain one as above JSON then one should be removed from the templateMapper

like image 331
user11229655 Avatar asked Apr 10 '26 05:04

user11229655


1 Answers

You can use Object.fromEntries to build object back from filtered entries

Here idea is:-

  • First get the entries from template object
  • Filter the entries based on filter value
  • Use Object.fromEntries to build object from filtered entries

const filter = { filterRows: ['one'] };

const template = {'one': {title: 'one',},'two': {title: 'two',},'three': {title: 'three',}}

const filterDialogView = filter.filterRows;
const final = Object.entries(template).filter(([row])=> !filterDialogView.includes(row))
console.log(Object.fromEntries(final));

If you environment doesn't support Object.fromEntries you can use this

const filter = { filterRows: ['one'] };

const template = {'one': {title: 'one',},'two': {title: 'two',},'three': {title: 'three',}}

const filterDialogView = filter.filterRows;
const final = Object.entries(template).filter(([row])=> !filterDialogView.includes(row))

const output = final.reduce((op,[key,value])=>{
  op[key] = value
  return op
},{})
console.log(output);
like image 96
Code Maniac Avatar answered Apr 12 '26 19:04

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!