Home > Blockchain >  Having an issue converting an object to a filtered array
Having an issue converting an object to a filtered array

Time:03-29

I'd like to filter and restructure some specific data, but I'm having some trouble getting it to produce the proper structure.

I have this data response in this structure....

var response = {
   badProperty1: "bad property text"
   goodProperty1: "abc"
   goodProperty2: "bcd"
   goodProperty3: "cde"
   goodProperty4: "def"
   goodProperty5: "efg"
   badProperty2: "fgh"
};

I'd like to convert my response object into an array like this structure exactly...

var newFilteredStructuredArray = [
   {goodProperty1: 'abc'},
   {goodProperty2: 'bcd'},
   {goodProperty3: 'cde'},
   {goodProperty4: 'def'},
   {goodProperty5: 'fgh'}
];

However I'd like to filter out the bad properties before I get my new array. I'd like my array to only include these specific property names and filter everything else that I started with.

var possiblePropertyNames = ['goodProperty1', 'goodProperty2', 'goodProperty3', 'goodProperty4', 'goodProperty5'];

CodePudding user response:

an implementation using filter and map on the object entries of response. In the filter stage I filter out only if it is available in possiblePropertyNames. Then in the map stage I return the array in the format you need

var possiblePropertyNames = ['goodProperty1', 'goodProperty2', 'goodProperty3', 'goodProperty4', 'goodProperty5'];
var response = {badProperty1: "bad property text",goodProperty1: "abc",goodProperty2: "bcd",goodProperty3: "cde",goodProperty4: "def",goodProperty5: "efg",badProperty2: "fgh"}

var newFilteredStructuredArray = Object.entries(response).filter(([k,v]) => possiblePropertyNames.includes(k)).map(([k,v]) => ({[k]:v}))

console.log(newFilteredStructuredArray)

without es6

var possiblePropertyNames = ['goodProperty1', 'goodProperty2', 'goodProperty3', 'goodProperty4', 'goodProperty5'];
var response = {badProperty1: "bad property text",goodProperty1: "abc",goodProperty2: "bcd",goodProperty3: "cde",goodProperty4: "def",goodProperty5: "efg",badProperty2: "fgh"}

var newFilteredStructuredArray = Object.keys(response)
.filter(function(a){
    return possiblePropertyNames.includes(a)
})
.map(function(b){
    return {[b]:response[b]}
})

console.log(newFilteredStructuredArray)

  • Related