组合JSON数据集(Combining JSON Data Sets)
假设我有以下两个数据集:
{ "food": { "apple": { "color": "red" }, "orange": { "color": "orange" }, "potato": { "color": "brown" }, "tomato": { "color": "red" } } }和
{ "fruits": { "apple": { "isFruit": "yes" }, "orange": { "isFruit": "yes" }, "tomato": { "isFruit": "yes" } } }有没有办法将这两组结合起来,使它们最终看起来像:
{ "food": { "apple": { "color": "red", "isFruit": "yes" }, "orange": { "color": "orange", "isFruit": "yes" }, "potato": { "color": "brown" } "tomato": { "color": "red", "isFruit": "yes" } } }我假设必须有一些方法来解析这两个集并将它们组合起来,但我无法弄清楚如何。
Let's say I have the following two data sets:
{ "food": { "apple": { "color": "red" }, "orange": { "color": "orange" }, "potato": { "color": "brown" }, "tomato": { "color": "red" } } }and
{ "fruits": { "apple": { "isFruit": "yes" }, "orange": { "isFruit": "yes" }, "tomato": { "isFruit": "yes" } } }Is there a way to combine these two sets so that they end up looking like:
{ "food": { "apple": { "color": "red", "isFruit": "yes" }, "orange": { "color": "orange", "isFruit": "yes" }, "potato": { "color": "brown" } "tomato": { "color": "red", "isFruit": "yes" } } }I assume there must be some way to parse these two sets and combine them but I haven't been able to figure out how.
最满意答案
试试JavaScript 三元运算符 :
var firstJSON = { "food": { "apple": { "color": "red" }, "orange": { "color": "orange" }, "potato": { "color": "brown" }, "tomato": { "color": "red" } } }; var secondJSON = { "fruits": { "apple": { "isFruit": "yes" }, "orange": { "isFruit": "yes" }, "tomato": { "isFruit": "yes" } } }; for(var i in firstJSON.food) { secondJSON.fruits.hasOwnProperty(i) ? firstJSON.food[i].isFruit = secondJSON.fruits[i].isFruit : ''; } console.log(firstJSON);Try JavaScript ternary operator :
var firstJSON = { "food": { "apple": { "color": "red" }, "orange": { "color": "orange" }, "potato": { "color": "brown" }, "tomato": { "color": "red" } } }; var secondJSON = { "fruits": { "apple": { "isFruit": "yes" }, "orange": { "isFruit": "yes" }, "tomato": { "isFruit": "yes" } } }; for(var i in firstJSON.food) { secondJSON.fruits.hasOwnProperty(i) ? firstJSON.food[i].isFruit = secondJSON.fruits[i].isFruit : ''; } console.log(firstJSON);
更多推荐
发布评论