json - 循环遍历 JSON 中具有相同属性的未知标识符(和未知数量)
问题描述
我正在使用 node.js 进行编程。
这是我将收到的 JSON 的简化示例:
{
"Transaction ID213": {
"drink": "milk",
"food": "eggs",
"mealType": "breakfast"
},
"Transaction ID432": {
"drink": "beer",
"food": "steak",
"mealType": "brunch"
},
"Transaction ID908": {
"drink": "water",
"food": "tacos",
"mealType": "dinner"
},
"Transaction ID776": {
"drink": "orange juice",
"food": "waffles",
"mealType": "breakfast"
}
}
我知道每个事务 ID 中的所有属性键。但是,我将/不知道交易 ID 或我将收到多少对象 (id)。样本中有 4 个对象 ID。可能会有多达 20,000 个或只有 1 个。数量未知。
对于每个事务 id,我会将每个键的值发布到 api。我将值映射到另一种 JSON 格式。例如:
{
"PROCESS_MEAL_Input": {
"LIQUID": TransactionID213.drink,
"SOLID": TransactionID213.food,
"TYPE": TransactionID213.mealType
}
}
我无法知道 TransactionID213,但我知道其中的键。
我想知道是否有一种方法可以使用 for 循环或其他循环结构来获取第一个对象(未知的 TransactionID213),发布其中的属性,然后移动到下一个对象。继续此过程,直到 JSON 中不再有对象。谢谢你。
解决方案
也许你需要这样的东西?
var obj = {
"Transaction ID213": {
drink: "milk",
food: "eggs",
mealType: "breakfast"
},
"Transaction ID432": {
drink: "beer",
food: "steak",
mealType: "brunch"
},
"Transaction ID776": {
drink: "water",
food: "tacos",
mealType: "dinner"
},
"Transaction ID777": {
drink: "orange juice",
food: "waffles",
mealType: "breakfast"
}
};
var arr = [];
for (let p in obj) {
let newObj = {
PROCESS_MEAL_Input: {
LIQUID: obj[p].drink,
SOLID: obj[p].food,
TYPE: obj[p].mealType
}
};
//POST here. http.request(.... Or something
arr.push(newObj);
}
console.log(arr);
推荐阅读
- if-statement - 如何为 Google 表格上的多个单元格应用 Arrayformula,其中包括固定单元格和可变单元格?
- visual-studio - 如何在 Visual Studio 中使用 IntelliCode?
- blueprism - Blue Prism:是否可以在 Spys 上设置计时器?
- c++ - 在 NVidia 的 W10 下使用 VS2019 构建计算 cpp sdk 的任何特殊步骤
- c++ - 如何在 C++ 中将对象添加到数组中?
- laravel - 如何从我的 laravel 项目的公共文件夹中删除文件
- r - 在R中按降序交换列之间的值
- java - 如何在 Android 中创建 Firebase 后台服务?
- ios - FCM 推送通知如何获取数据并显示自定义横幅
- angular - firebase auth/unauthorized-domain 错误,虽然我授权了域