前端006/数据处理

时间:2021-09-05 13:46:24

React框架--遍历json数组

packJson = [
    {"name":"nikita", "password":"1111"},
    {"name":"tony", "password":"2222"}
];

for(var p in packJson){//遍历json数组时,这么写p为索引,0,1
   alert(packJson[p].name + " " + packJson[p].password);
}

//或

for(var i = 0; i < packJson.length; i++){
   alert(packJson[i].name + " " + packJson[i].password);
}

项目示例1:

//secretListData数据格式:
[
{id:123,name='test1'},
{id:456,name='test2'}
]

<ant-FormItem label="xxx:">
  <#SignKey>
    <ant-Select showSearch filterOption={handleFilter} style="width: 100%" placeholder="请选择" onChange={handleChange}>
      <#each {{secretListData}}>
      <ant-Option value="{@item.id}">{@item.name}</ant-Option>
      </#each>
    </ant-Select>
  </#SignKey>
</ant-FormItem>

//map用法
handleChange = (e) => {
    secretListData.map((item, key) => {
      if(item.id == e) {
        console.log(item.name)
      }
    });
  }

//filter用法
handleChange = (e) => {
    secretListData.filter(item => {
      if(item.id == e) {
        console.log(item.name)
      }
    });
  }

项目示例2:

//数据格式
result={key1:value1,key2:value2}

//组装成格式
[{key1:value1},{key2:value2}]

//React-table组件需要组装成该格式

let table=[];
let newResult={};
for(var key in result){ newResult={id:key,name:result[key]}; table.push(newResult); }

 

参考博客:

javascript处理json