首页 > 解决方案 > 循环遍历 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 中不再有对象。谢谢你。

标签: jsonnode.jsfor-loopkey-value

解决方案


也许你需要这样的东西?

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);


推荐阅读