Reputation: 2527
This is my original Object:
Data = {
aesthetic: {
heritage: 'aesthetic',
description: 'sdokjosk',
value: 5
},
architectural: {
heritage: 'architectural',
description: 'doodsjdj',
value: 1
},
historical: {
heritage: 'historical',
description: 'dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ',
value: 4
},
score: 3
};
i want to write a function that goes through the object and converts the properties only with 'heritage' 'description' and 'value' into an array that would look like this:
[{
"heritage": "aesthetic",
"description": "sdokjosk",
"value": 5
},
{
"heritage": "architectural",
"description": "doodsjdj",
"value": 1
},
{
"heritage": "historical",
"description": "dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ",
"value": 4
}
]
This is what I have tried:
Object.values(Data)
but this returns an array with the 3 from the score property at the end
Upvotes: 0
Views: 35
Reputation: 753
If you want to check all the keys you mentioned should present you can go with this :
Object.values(Data).filter(function(data){return data["heritage"] && data["description"] && data["value"]})
Upvotes: 1
Reputation: 32175
You can use Object.values()
method to get the array
of values, then filter only objects from it using Array#filter()
method.
This is how should be your code:
var result = Object.values(Data).filter(x => typeof x == 'object');
Demo:
This is a working demo snippet:
var Data = {
aesthetic: {
heritage: 'aesthetic',
description: 'sdokjosk',
value: 5
},
architectural: {
heritage: 'architectural',
description: 'doodsjdj',
value: 1
},
historical: {
heritage: 'historical',
description: 'dcnsdlnckdjsncksdjbk kjdsbcjisdc hsdk chjsd cjhds ',
value: 4
},
score: 3
};
var result = Object.values(Data).filter(x => typeof x == 'object');
console.log(result);
Upvotes: 2