微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

比较两个键值对象的值

如何解决比较两个键值对象的值

我有两个对象(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>

解决方法

Object.keys(labels1) 将返回项目索引数组,而不是 id,因为 labels1labels2 是数组。您必须循环抛出数组之一的所有项目,并尝试在第二个项目中找到匹配项

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= LABELS1;
    var labels2= LABELS2;
        
      for(const label1 of labels1) {
        const label2Index = labels2.findIndex(label2 => label2.id === label1.id)
        if(label2Index != -1) {
          label1.simple_value = labels2[label2Index].simple_value
        }

      }
     console.log(labels1) 

    
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

,

您可以将标签 (#2) 缓存到它们的索引中,然后在将标签 (#1) 映射到它们的 simple_value 时通过其索引检索标签 (#2)。

const
  LABELS_1 = [
    { "id": "bread","simple_value": "Bread" },{ "id": "apple","simple_value": "Apple" }
  ],LABELS_2 = [
    { "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" }
  ];

// Cache the labels (#2) to their index
const idToIndex = LABELS_2.reduce((acc,{ id },index) =>
  ({ ...acc,[id]: index }),{});

const labels = LABELS_1.map(({ id,simple_value }) => ({
  id,simple_value: ((index) =>
    LABELS_2[index]?.simple_value || simple_value)
  (idToIndex[id]) 
}));

console.log(labels);
.as-console-wrapper { top: 0; max-height: 100% !important; }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。