Convert and add props of the object type into data of the array type


#1

I have props with object type, for example:

animals: { 
  animals: true, 
  residentCount: 5
},
residents: { 
  icon: "people", 
  text: "Residents", 
  value: "5"
 }

and I have to add this objects into data of component of array type, and this must be as follows:

details:[
  { 
    icon: "animals", 
    text: "Pets", 
    value: "Да" 
  },  
  { 
    icon: "people", 
    text: "Residents", 
    value: "5"
   }
]

How can I resolve this case?


#2

Any ideas?


#3

Hi,
Your animals and residents object doesn’t have same structure.

Maybe I don’t understand what you want but it’s not possible to make a script for convert all object if you don’t have a similar structure.

Where does the text: "Pets" and value: "Да" come from ?


#4

Yes, actually, I didn’t write the example correctly, it looks as follows:

Objects:

    animals: {
      value: true
    },
    badHabbits: {
      value: true
    }

After converting:
Array

details:[
  { 
    icon: "animals", 
    text: "Pets", 
    value: "Yes" 
  },  
  { 
    icon: "habbits", 
    text: "Bad habbits", 
    value: "Yes"
  }
]

#5

It’s the same thing.

In your example, we don’t know where you get your attribute value.
There is no link between your first and second object.
For the animals, the icon attribute becomes the variable name but not for the badHabbits.
And for your text attribute, there is no link with you first objects…


#6

OK, here is more detailed example:

I have one big object:

facilities: {
  fridge: {
    text: 'Холодильник',
    value: true
  },
  cooker: {
    text: 'Плита',
    value: true
  },
  washer: {
    text: 'Стиральная машина',
    value: false
  }
}    

result:
Array without icons

details:[
  {     
    text: "Холодильник", 
    value: "Yes"
  },  
  { 
    text: "Плита", 
    value: "Yes"
  }
]

If the value is false in the object, then it must not be in the converted array


#7

Hi,
So, you can make this with filter Array function like this

cont details = Object.values(facilities).filter((item_) => { return item_.value === true; })

#8

Hi,
I think you didn’t get it. I need to convert component props of object type into data of array type. It should look like this:

<script>
  export default {
    props: {
      facilities: {
        type: Object,
        required: true
      }
    },
    data: ()=> ({
      comfort: [
      {
        text: 'Электроплита',
        id: 1   
       },
       {
         text: 'Стиральная машина',
         id: 2
       }
     ]
   })
 }
</script>

#9

Sorry, I used your solution in my way and it worked.
Here it is:

<script>
export default {
  props: {
    facilities: {
      type: Object,
      required: true
    }
  },
  computed: {
    comfort: {
      get(){
        return Object.values(this.facilities).filter((item_) => { 
          return item_.value === true 
        })
      }
    }
  }
}
</script>