【发布时间】:2021-07-10 17:13:19
【问题描述】:
我有两个要循环的对象(LABELS1 和 LABELS2),如果 LABELS1 中的任何 ID 与 LABEL2 中的任何 ID 匹配,那么我想用 LABELS2 中的 simple_value 重新分配 LABELS1 的 simple_value。但是,每当我比较这些值时,都没有匹配。这是我在下面尝试过的。任何帮助将不胜感激。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
const LABELS1 = [
{"id":"bread", "simple_value":"Bread"},
{"id":"apple", "simple_value":"Apple"}
];
const LABELS2 = [
{"id":"bread", "simple_value":"Bread with Butter", "detailed_value":"Toasted Bread with a Dab of Butter"},
{"id":"wine", "simple_value":"Wine", "detailed_value":"Wine with Cheese"}
];
var labels1= [];
var labels2= [];
$.when(
$.getJSON(LABELS1, json => {
labels1= json;
}),
$.getJSON(LABELS2, json => {
labels2= json;
})
).then(() => {
Object.keys(labels1).forEach(key => {
if (labels2[key].id=== labels1[key].id) {
labels1[key].simple_value= labels2[key].simple_value;
}
});
});
</script>
</body>
</html>
【问题讨论】:
标签: javascript json for-loop foreach key-value