组合JSON数据集(Combining JSON Data Sets)

编程入门 行业动态 更新时间:2024-10-27 02:20:20
组合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); 
  
 

更多推荐

本文发布于:2023-08-06 07:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1445271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   数据   JSON   Sets   Combining

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!