javascriptobjectiterationfiltered

How select items in an object from an array of undesired key and create a new object with the result


Maybe it's a weird question, and maybe that exists and other way to make that... But, I've an initial Object on which I iterate on the key. For a special task, I've needed to have this Object without some key:value. For doing that I make an object with the key that I don't want.

I make this code pen for sample: https://codepen.io/charlene-bx/pen/qBXaqEL

const myInitialObject = {
  'key#one' : 'dataofanotherObject',
  'key#two' : 'dataofanotherObject',
  'key#three' : 'dataofanotherObject',
  'key#four' : 'dataofanotherObject',
  'key#five' : 'dataofanotherObject',
  'key#six' : 'dataofanotherObject',
  'key#seven' : 'dataofanotherObject',
  'key#eight' : 'dataofanotherObject',
  'key#nine' : 'dataofanotherObject',
  'key#ten' : 'dataofanotherObject'
}

const unDesiredKey = [
  'one',
  'four',
  'six'
]

// expected output:
// {
//  'key#two' : 'dataofanotherObject',
//  'key#three' : 'dataofanotherObject',
//  'key#five' : 'dataofanotherObject',
//  'key#seven' : 'dataofanotherObject',
//  'key#eight' : 'dataofanotherObject',
//  'key#nine' : 'dataofanotherObject',
//  'key#ten' : 'dataofanotherObject'
// }

I've found this solution but I can't find it very readable:

const filteredObject = Object.keys(myInitialObject)
      .filter(key => !unDesiredKey.map( el => !key.includes(el)).some(el => el===false))
      .reduce((accumulator, value) => ({...accumulator, [value]: myInitialObject[value]}), {})

Solution

  • You could do this,

    Use Array.prototype.map() on Object.entires() to filter out an array of desired key-value pair. And finally construct a new object from the key-value pair using Object.fromEntries()

    const myInitialObject = {
        'key#one': 'dataofanotherObject',
        'key#two': 'dataofanotherObject',
        'key#three': 'dataofanotherObject',
        'key#four': 'dataofanotherObject',
        'key#five': 'dataofanotherObject',
        'key#six': 'dataofanotherObject',
        'key#seven': 'dataofanotherObject',
        'key#eight': 'dataofanotherObject',
        'key#nine': 'dataofanotherObject',
        'key#ten': 'dataofanotherObject'
    }
    
    const unDesiredKey = [
        'one',
        'four',
        'six'
    ]
    
    const arr = Object.entries(myInitialObject).filter(x => !unDesiredKey.includes(x[0].split('#')[1]));
    
    const finalObj = Object.fromEntries(arr);
    console.log(finalObj)