Home > Software engineering >  How to convert 1 to Yes or 0 to No in array?
How to convert 1 to Yes or 0 to No in array?

Time:08-31

I have data which is coming in 1 and 0 from db and I need to show in UI Yes and No. I am using for (const obj of arr1) and map like stuff and still not able to get the desire output.

const arr = [
  {id: 1, name: 'Emp1', lc: 1},
  {id: 2, name: 'Emp2', lc: 0},
  {id: 3, name: 'Emp3', lc: true},
  {id: 4, name: 'Emp4', lc: false},
];

I need to convert this array this way

const newArr = [
  {id: 1, name: 'Emp1', lc: "Yes"},
  {id: 2, name: 'Emp2', lc: "No"},
  {id: 3, name: 'Emp3', lc: "Yes" },
  {id: 4, name: 'Emp4', lc: "No"},
];

CodePudding user response:

const arr = [
  {id: 1, name: 'Emp1', lc: 1},
  {id: 2, name: 'Emp2', lc: 0},
  {id: 3, name: 'Emp3', lc: true},
  {id: 4, name: 'Emp4', lc: false},
];

const newArray = arr.map((item) => ({
  ...item,
  lc: item.lc ? 'Yes' : 'No'
  })
  )
  console.log(newArray)
  

This creates a new array. ...item puts in all the existing fields. lc: item.lc ? 'yes' : 'no' basically creates a new value for lc where if the value is truthy (1, or true) it give you Yes, and otherwise if gives you No

CodePudding user response:

You can try this.

const newArr = arr.map(elem => {
   elem.lc = elem.lc ? "Yes" : "No";
   return elem
})

CodePudding user response:

just map and update it

const newArr = arr.map((a)=>{
  a.lc = a.lc ? "Yes" : "No";
    return a;
});
  • Related