使用Handlebars获取同级JSON数据,其中单个对象没有父索引键,但多个项有一个索引键

Getting sibling JSON data with Handlebars, where a single object has no parent index key, but multiple items have an index key?

本文关键字:索引 有一个 单个 获取 Handlebars JSON 数据 使用 对象      更新时间:2023-09-26

我遇到了一个有趣但令人讨厌的情况,我从API获取了一些数据,这些数据暴露了使用Handlebars等模板语言的缺点。(帮助者,帮助者无处不在!

是否有一种干净的方法来处理以下情况。从本质上讲,如果一个JSON对象只有一个兄弟对象,那么它就没有用键包装,但如果它返回多个,那么它们就用键包装

因此,下面我们有一个例子,其中的成分有一个兄弟,它在没有包装的情况下返回。第二个对象返回2个成分,因此它们被一个索引键包裹。

我真的对数据的外观无能为力,我只需要能够处理它。

我假设一个助手是可行的,但我希望有一个巧妙的技巧来处理以下情况,以便根据返回的数据来捕捉两者。如果可能的话,我也更喜欢使用纯Handlbar(没有Ember等的帮助)。

如果有人能帮忙,我将不胜感激!

场景1:

"food":{
  "ingredient":{
    "name":"Cucumber",
    "weight":"5",
    "cost":"1",
  }
}

场景2:

"food":{
 "ingredient":{
  "1":{
     "name":"Cheese",
     "weight":"10",
     "cost":"2"
  },
  "2":{
     "name":"Tomato",
     "weight":"20",
     "cost":"0.5"
    }
 }
}

解决方案:

packageResponse()函数将以与您提到的每个场景相同的方式返回ingredient数据:

/*  ===================
    SUPPORT FUNCTION(s)
    =================== */
function isKeyNumeric(key){
    var test = Number(key);
    if(isNaN(test))
        return false;
    return true;
}

/*  =============
    MAIN FUNCTION
    =============   */
function packageResponse(ingredient){
    var ingredients = {}
    var count = 0
    for(var i in ingredient){
        //  Breakpoint in case we get a prototype property
        if( !ingredient.hasOwnProperty(i) ) continue;
        //  Test for what method to use
        if( isKeyNumeric(i) ){
            //  Add the wrapped ingredient
            ingredients[count++] = ingredient[i]
        }else{
            //  Add the unwrapped ingredient
            ingredients[0] = ingredient
            break
        }//endifelse
    }//endfor
    return ingredients
}//endfunction

测试:

/*  =========
    TEST DATA
    =========   */
var response_one = {"food":{
    "ingredient":{
        "name":"Cucumber",
        "weight":"5",
        "cost":"1",
        }
    }
}
var response_two = {"food":{
    "ingredient":{
        "1":{
            "name":"Cheese",
            "weight":"10",
            "cost":"2"
            },
        "2":{
            "name":"Tomato",
            "weight":"20",
            "cost":"0.5"
            }
        }
    }
}
/*  ===========
    TEST OUTPUT
    =========== */
console.log( packageResponse(response_one.food.ingredient) )
console.log( packageResponse(response_two.food.ingredient) )

输出:

上面的代码生成这个控制台输出:

第一个日志:

0: Object
  cost: "1"
  name: "Cucumber"
  weight: "5"

第二日志

0: Object
  cost: "2"
  name: "Cheese"
  weight: "10"
1: Object
  cost: "0.5"
  name: "Tomato"
  weight: "20"
相关文章: