首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JavaScript数组中存储相同的键值和不同的值,并与键值对匹配

在JavaScript数组中存储相同的键值和不同的值,并与键值对匹配
EN

Stack Overflow用户
提问于 2016-12-13 14:21:20
回答 1查看 1.5K关注 0票数 3
代码语言:javascript
复制
     $(document).on('change', '.units', function () {
            var obj = $(this);
            unit_id = parseInt($(this).val());
            var item_array = [];
            var unit_array = [];
            var units = $(".units");
            var items = $(".items");

            $('#used_items tr').each(function () {
                $(this).find('.items').each(function () {
                    item_array.push($(this).val());
                });
                $(this).find('.units').each(function () {
                    unit_array.push($(this).val());
                });
            });
            var item_unit_associative_array = [];
            for (var i = 0; i < units.length; i++) {
                if (item_unit_associative_array[item_array[i]] == unit_array[i]) {
                    obj.val('');
                    return alert("Given Item Unit Already Selected");
                }
                else {
                    item_unit_associative_array[item_array[i]] = unit_array[i];
                }
            }
            console.log(item_unit_associative_array););

item_arrayunit_array,我想构建新的对象,如

var item_unit_associative_array=1:12,1:13 ,1:14,2:10;

最后,要检查由键组成的对象:值,类似

var test ={1:12}

是否存在于item_unit_associative_array中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-13 14:42:00

我认为你需要嵌套两层物体。请参见对结构的评论:

代码语言:javascript
复制
var items = [ 1,  1,  1,  2];
var units = [12, 13, 14, 10];

// Create the object like so:
// { 
//   1: { 12: true, 13: true, 14: true },
//   2: { 10: true }
// }
var itemUnitAssociativeObject = {};
units.forEach(function(unitId, i) {
  var itemId = items[i];  
  if (!itemUnitAssociativeObject[itemId]) {
    itemUnitAssociativeObject[itemId] = {};
  }
  
  itemUnitAssociativeObject[itemId][unitId] = true;
});

console.log("1:13", test(1, 13));
console.log("1:10", test(1, 10));
console.log("2:10", test(2, 10));

function test(item, unit) {
   return !!(itemUnitAssociativeObject[item] &&
     itemUnitAssociativeObject[item][unit]);
}

如果您不喜欢嵌套以及它使测试复杂化的方式,您还可以“限制”项单元id组合:

代码语言:javascript
复制
var items = [ 1,  1,  1,  2];
var units = [12, 13, 14, 10];

// Create the object like so:
// { 
//   "1:12": true,
//   "1:13": true, // etc.
// }
var map = items.reduce(function(map, itemId, i) {
  var id = itemId + ":" + units[i];
  map[id] = true;
  return map;
}, {});

console.log("1:13", map["1:13"]);
console.log("1:10", map["1:10"]);
console.log("2:10", map["2:10"]);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41123397

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档