假设你有一个数组,包含了多个对象,每个对象都有'fl_name'、'is_selected'和'_id'三个属性。你需要从这个数组中找到'is_selected'属性值为1的对象,并提取其'_id'值。

例如,你的数组可能是这样的:

[{fl_name: '全天房费率',is_selected: 0,_id: '3yb2pa0hfkxf'},{fl_name: '半天房费率',is_selected: 1,_id: '3yb2pa0hfkxd'}]

你需要找到'_id'值为'3yb2pa0hfkxd'的对象。

可以使用以下方法来实现:

  1. 循环遍历数组:遍历数组中的每个对象,判断其'is_selected'属性是否为1,如果是,则获取其'_id'值。

  2. 使用Array.filter()方法:使用filter方法筛选出'is_selected'属性为1的对象,再从筛选后的数组中获取第一个对象的'_id'值。

  3. 使用Array.find()方法:使用find方法直接找到第一个'is_selected'属性为1的对象,并获取其'_id'值。

以下是一个使用JavaScript代码示例:

const data = [{fl_name: '全天房费率',is_selected: 0,_id: '3yb2pa0hfkxf'},{fl_name: '半天房费率',is_selected: 1,_id: '3yb2pa0hfkxd'}];

// 使用循环遍历
for (const item of data) {
  if (item.is_selected === 1) {
    console.log(item._id);
    break;
  }
}

// 使用Array.filter()方法
const filteredData = data.filter(item => item.is_selected === 1);
console.log(filteredData[0]._id);

// 使用Array.find()方法
const targetItem = data.find(item => item.is_selected === 1);
console.log(targetItem._id);

无论使用哪种方法,你都可以成功地从数组中找到'is_selected'属性值为1的'_id'值。

如何从数组中获取is_selected为1的_id值

原文地址: https://www.cveoy.top/t/topic/qxUU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录