如何从嵌套数组状态获取特定索引?

时间:2018-10-22 11:54:52

标签: arrays reactjs

你好,我有这样的状态; <​​/ p>

{
  "id": "8",
  "tablename": "demo_1",
  "segments": "segment_1"
},
{
  "id": "9",
  "tablename": "demo_2",
  "segments": "segment_2"
}

我想从segments中提取tablename个值。像这样:

this.state.MYSTATE.map[tablename:'demo_1'];

但是这不会起作用。有帮助吗?

2 个答案:

答案 0 :(得分:1)

您需要的是一个filter,然后是一个map

const data = [{
  "id": "8",
  "tablename": "demo_1",
  "segments": "segment_1"
},
{
  "id": "9",
  "tablename": "demo_2",
  "segments": "segment_2"
}]

const segments = data
  .filter(item => item.tablename === 'demo_1')
  .map(item => item.segments)
  
console.log(segments)

过滤器将过滤所有表名等于demo_1的条目,并且map将返回这些过滤结果的细分值

答案 1 :(得分:1)

您可以将.findIndex()方法用于数组。

this.bubbleEvent() is not a function方法返回满足提供的测试功能的数组中第一个元素的索引。否则,它返回-1,表示没有元素通过测试。

演示

findIndex()
const data =[{
    "id": "8",
    "tablename": "demo_1",
    "segments": "segment_1"
  },{
    "id": "9",
    "tablename": "demo_2",
    "segments": "segment_2"
  }];
  
let index = data.findIndex(({tablename})=>tablename=='demo_1');

console.log(index);