2

I'm trying to show specific series of specific fields and value inside of the object but it's not working.

var objArray = [
    {id:1, photo:true, bol: true }, {id:2, photo: true, bol:true}
];

result = objArray.map((item) => return {id: item.id, photo: item.photo 
}) // this doesn't work.. why??

Expectd Output

[
    {id:1, photo:true}, {id:2, photo: true}
]
hellofanengineer
  • 3,583
  • 6
  • 37
  • 81

2 Answers2

4

You need to make two changes

  • Remove return statement - arrow functions will implicitly return the expression's evaluated result.
  • Wrap {} with () so that {} doesn't get treated as a code block, but as an expression.

i.e.

objArray.map((item) => ({id: item.id, photo: item.photo  }));

Demo

var objArray = [{
  id: 1,
  photo: true,
  bol: true
}, {
  id: 2,
  photo: true,
  bol: true
}];

var result = objArray.map((item) => ({
  id: item.id,
  photo: item.photo
}));

console.log(result);
gurvinder372
  • 61,170
  • 7
  • 61
  • 75
1

Create temporary Object;

Iterate through object and if key is not "bol", then push it to temp Object;

finally return the temporary Object

var objArray = [
    {id:1, photo:true, bol: true }, {id:2, photo: true, bol:true}
];


result = objArray.map((item) => {
let tempObj = {}
 Object.keys(item).map((key) => {   
   if(key != "bol") {
      tempObj[key] = item[key]
      
   }     
 })
 return tempObj;
 })
 
 console.log(result)
Rajkumar Somasundaram
  • 1,153
  • 1
  • 9
  • 15