const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const allowed = ['item1', 'item3'];
const filtered = Object.keys(raw)
.filter(key => allowed.includes(key))
.reduce((obj, key) => {
obj[key] = raw[key];
return obj;
}, {});
console.log(filtered);
Run code snippet
const raw = {
item1: { key: 'sdfd', value:'sdfd' },
item2: { key: 'sdfd', value:'sdfd' },
item3: { key: 'sdfd', value:'sdfd' }
};
const allowed = ['item1', 'item3'];
const filtered = Object.keys(raw)
.filter(key => allowed.includes(key))
.reduce((obj, key) => {
obj[key] = raw[key];
return obj;
}, {});
console.log(filtered);
Run code snippet
const person = {
first_name: 'John',
last_name: 'Smith',
id: '0000-0000-0000-0001',
email: 'js-example.example.com',
taxID: '000-111-5555'
}
const displayOnly = ['first_name', 'last_name', 'email']
//Object.fromEntries converts Object.entries back into an object
const results = Object.fromEntries(
//Object.entries creates an array of the key value pairs in the object.
Object.entries(person).filter(entry => {
const property_name = entry[0];
//filter out keys based on the array
if (displayOnly.includes(property_name)) {
return entry
}
})
);
console.log(results)