gpt4 book ai didi

javascript - 访问nodejs中各个级别的嵌套JSON对象

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:28 29 4
gpt4 key购买 nike

我将数据存储在这样的变量中

var products = [
{
place1:[
{id: 1, name: "choc1", price: 20},
{id: 2, name: "choc2", price: 30}
],
place2:[
{id: 1, name: "coffee", price: 50}
],
place3: [
{id: 1, name: "oil1", price: 10},
{id: 2, name: "oil2", price: 60},
{id: 3, name: "oil3", price: 70}
]
}
];

我想写一个get方法,让它响应这个Url

http://myurl.com/place1/1

获取方法的格式为

router.get('/:place/:id([0-9]{1,})', function(req, res){
// send the exact data as requested
}

我不明白的是如何验证链接。即,验证该位置是否在 products 变量中,然后验证该 id 是否存在于该产品变量中,如果存在,则将其发送回服务器,否则发送错误响应。

最佳答案

这是使用点表示法从对象获取嵌套值的函数:

/**
* Treating field name with dot in it as a path to nested value.
* For example 'settings.day' is path to { settings: { day: 'value' } }
*
* @param {{}} object Object where to look for a key
* @param {string} field Dot notated string, which is path to desired key
* @returns {*}
*/
getNestedValue = function (object, field) {
if (!object) {
return null;
}

var path = field.split('.');
while (path.length && (object = object[path.shift()]));

return object;
};

关于javascript - 访问nodejs中各个级别的嵌套JSON对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44062883/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com