如何比较2阵列在一个更新键值对? [英] How to compare 2 Arrays to update key value pairs in one?

查看:145
本文介绍了如何比较2阵列在一个更新键值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有标记的主阵列

var tagsArray = [
    {
        name: "1",
        selected: undefined
    },
    {
        name: "2",
        selected: undefined
    },
    {
        name: "3",
        selected: undefined
    }
]

然后选择标记的数组进行比较:

Then an array of selected tags to compare it to:

var selectedTags = [
    {
        name: "1",
        selected: true
    }
]

你会如何运行一些比较(for循环)来检查 selectedTags 哪些对象有选择:真价值?

然后还设置了同一个对象的 tagsArray 真正

Then also set the same object's selected value in tagsArray to true?

推荐答案

创建一个访问地图,然后遍历并找到真正值和其他数组中设置的值

Create an access map, then iterate and find the true values and set the values in the other array

var map = {};

tagsArray.forEach(function(obj, index) {
    map[obj.name] = index;
});

selectedTags.forEach(function(obj) {
    if ( obj.selected ) {
        tagsArray[map[obj.name]].selected = true;
    }
});

FIDDLE

这篇关于如何比较2阵列在一个更新键值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆