Home > Mobile >  How to add a property to my object using a map
How to add a property to my object using a map

Time:04-12

I want to add this "visible" attribute and change my "countries" array, "el2" is being changed correctly, but my array at the end is not as expected.

The elements are entering the conditionals and being added to the new property, but at the end of the loop the array is not coming out as expected

      const countryVisible: any = ['EUA', 'CANADA']
      const countries: any = [{name: 'EUA', id: '123'}, {name: 'CANADA', id: '321'}, {name: 'Italia', id: '322'}]

      countries.map((el2, index2) => {
        countryVisible.forEach((el, index) => {
          if (el2['name'] === el) {
             el2 = {...el2, visible: true}
            console.log(el2) // {name: 'EUA', id: '123', visible: true} and {name: 'CANADA', id: '321', visible: true}
          } else {
            el2 = {...el2, visible: false}
            console.log(el2) //{name: 'Italia', id: '322', visible: false}
          }
        })

      })

      console.log(countries)

output:

[
    {
        "name": "EUA",
        "id": "123"
    },
    {
        "name": "CANADA",
        "id": "321",
        "visible": false
    },
    {
        "name": "Italia",
        "id": "322",
        "visible": false
    }
]

output expected :

[
    {
        "name": "EUA",
        "id": "123",
        "visible": true
    },
    {
        "name": "CANADA",
        "id": "321",
        "visible": true
    },
    {
        "name": "Italia",
        "id": "322",
        "visible": false
    }
]

CodePudding user response:

You can replace forEach loop with .includes method

const countryVisible = ['EUA', 'CANADA'];
const countries = [{name: 'EUA', id: '123'}, {name: 'CANADA', id: '321'}, {name: 'Italia', id: '322'}];

const result = countries.map((country) => ({
  ...country, 
  visible: countryVisible.includes(country.name),
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

You can use this syntax to assign conditional property to JS object. (ES6)

const a = {
   ...(someCondition && {b: 5})
}

Or you can use Javascript Object.defineProperty built-in function

Object.defineProperty(obj, 'foo', {
  value: 1
})
  • Related