0

I have this object and I want to return a value when the field_id is equal to 40. How can I do this? In this case I want to return 111

  myObj = [{
   id: 11,
   company_id: 1,
   field_id: 7,
   value: 700,
},
  {
   id: 12,
   company_id: 1,
   field_id: 40,
   value: 111,
},
  {
   id: 13,
   company_id: 1,
   field_id: 41,
   value: 222,
 }]
Lizz Parody
  • 1,705
  • 11
  • 29
  • 48

3 Answers3

1
for(item of myObj) { if(item.field_id == 40) return item.value; }
Boric
  • 822
  • 7
  • 26
1

// Array with objects
myArr = [{
    id: 11,
    company_id: 1,
    field_id: 7,
    value: 700,
  },
  {
    id: 12,
    company_id: 1,
    field_id: 40,
    value: 111,
  },
  {
    id: 13,
    company_id: 1,
    field_id: 41,
    value: 222,
  }
];

myFilter = (arr, key, value, output) => arr.filter(o => o[key] === value).map(r => r[output]);

// Result is an array (if several solutions)
console.log(myFilter(myArr, "field_id", 40, "value"));
0

You need to loop through the array

var i;
for (i = 0; i < myObj.length; i++) { 
    if (myObj[i].field_id == 40) {
        return myObj[i].value
     }
}
Sacha
  • 322
  • 1
  • 8