【问题标题】:Get data from JSON dynamically从 JSON 动态获取数据
【发布时间】:2018-01-21 15:17:05
【问题描述】:

我有一个这样的 json:

{
   listOfOptions:[
     {
       valueType: "alphabet"
       possibleValues:["a","b"]
     },
     {
       valueType: "integer"
       possibleValues:["1","2"]
     }
   ]

我正在动态获取这些值名称,因此在我的反应函数中我想要相应的可能值:

所以我创建了一个这样的函数:

myjson.listOfOptions.map((item,index)=> {
    if(item.valueType==e)
      return item.possibleValues[0]
})

因此,如果我将“e”设置为整数,则在运行此程序时,我会得到: [null,"1"] 但我想要的是: "1"(只有“1”而不是[“1”])

我可以使用过滤器来获得预期的结果吗?

【问题讨论】:

    标签: arrays json reactjs ecmascript-6


    【解决方案1】:

    这是因为Array.map 返回的结果数组与输入数组的长度相同。对于输入数组中的第一个对象,回调函数返回null

    所以,我认为您正在寻找的是这样的东西;

    原答案

    myjson.listOfOptions
      .filter(item => item.valueType==e) // get just the items that match your filter condition
      .map(item => item.possibleValue[0]) // then get the sub attribute's values
    

    已编辑(在 cmets 中提问后)

    // get the first object that matches the search condition
    let result = myjson.listOfOptions.find(item => item.valueType==e) 
    // this will return the first element in the array `possibleValues` of that object that matches the search condition
    return result.possibleValues[0]; 
    

    专业提示:使用 lodash 之类的东西进行安全导航;所以返回语句看起来像_.get(result, 'possibleValues[0]', 'N/A')

    【讨论】:

    • 感谢这很有用,我能够删除 null 但我得到 ["1"] 但我想要的是 "1"
    • 那么你不想使用map,因为它总是会返回一个数组。也许你会想使用find,我已经用这个建议编辑了我的答案。
    【解决方案2】:

    可能的解决方案:

    let result = [];
    
    myjson.listOfOptions.forEach((item,index) => {
        if(item.valueType == e)
          result.push(item.possibleValues[0]);
    })
    
    console.log('result', result);
    

    或使用array.reduce

    result = myjson.listOfOptions.reduce((result, item, index)=> {
        if(item.valueType == e){
          result.push(item.possibleValues[0]);
        }
        return result;
    }, [])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 2016-06-22
      • 1970-01-01
      • 2020-04-09
      • 1970-01-01
      相关资源
      最近更新 更多