Reputation: 39
I have an object that contains many properties.
I need to extract only some of those properties for an array. The commonalities between the properties I need to extract are that myObject.property.type
will return 'integer' - but I also need to extract one more property that would return 'string'. Then, I will transform this object into an array using the Object.keys() function.
I'm looking for some efficient and stylish ways to do this.
What I have:
myObject: {
badProperty1: {type: 'object'},
goodProperty1: {type: 'integer'},
badProperty2: {type: 'object'},
goodProperty2: {type: 'string'},
badProperty3: {type: 'object'},
goodProperty3: {type: 'integer'},
}
What I want:
myArray = ['goodProperty1', 'goodProperty2', 'goodProperty3']
Upvotes: 0
Views: 950
Reputation: 7428
You can at first get all the keys, then filter them by a type
property value of the corresponding object for that key in the parent object. For example:
let myObject = {
badProperty1: {type: 'object'},
goodProperty1: {type: 'integer'},
badProperty2: {type: 'object'},
goodProperty2: {type: 'string'},
badProperty3: {type: 'object'},
goodProperty3: {type: 'integer'},
};
let result = Object.keys(myObject).filter(key => ['integer', 'string'].includes(myObject[key].type));
console.log(result)
Upvotes: 2