我有这个对象,我想在field_id等于40时返回一个值。我该怎么做?在这种情况下,我想返回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,
}]
答案 0 :(得分:1)
for(item of myObj) { if(item.field_id == 40) return item.value; }
答案 1 :(得分: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"));
答案 2 :(得分:0)
你需要循环遍历数组
var i;
for (i = 0; i < myObj.length; i++) {
if (myObj[i].field_id == 40) {
return myObj[i].value
}
}