将哈希值存储在另一个数组中

时间:2022-06-06 21:30:25

I have a list of key-value pairs and I am trying to store the key N times in another array. I'm struggling with the logic, if I iterate over the list_of_objects I can't see a way to keep track of which keys-values have already been assigned.

我有一个键值对列表,我试图将键存储在另一个数组中N次。我正在努力学习逻辑,如果我遍历list_of_objects,我看不到跟踪哪些键值已被分配的方法。

var kv={"a":2,"b":1,"c":1};
var list_of_objects=[bob,bill,jane,joe];//these are objects

GOAL

bob.kv="a"
bill.kv="a"
jane.kv="b"
joe.kv="c"

Notes in response to comment: kv is a property of the object bob (or bill, or jane, or joe)

响应评论的注释:kv是对象bob(或bill,或jane或joe)的属性

2 个解决方案

#1


1  

You might want to try Object.keys()

您可能想尝试Object.keys()

Object.keys(kv).forEach(function(key) {
  var val = kv[key];
  while(val-- > 0) {
    var obj = objects.shift();
    obj.kv = key;
    console.log(obj)
  }
});

#2


1  

Similar to @MatUtter's answer but does not mutate the list_of_objects array:

与@ MatUtter的答案类似,但不会改变list_of_objects数组:

var index = 0;
for (var key in kv) {
    if (kv.hasOwnProperty(key)) {
        var val = kv[key];
        while (val-- > 0) {
            list_of_objects[index].kv = key;
            index++;
        }
    }    
}

#1


1  

You might want to try Object.keys()

您可能想尝试Object.keys()

Object.keys(kv).forEach(function(key) {
  var val = kv[key];
  while(val-- > 0) {
    var obj = objects.shift();
    obj.kv = key;
    console.log(obj)
  }
});

#2


1  

Similar to @MatUtter's answer but does not mutate the list_of_objects array:

与@ MatUtter的答案类似,但不会改变list_of_objects数组:

var index = 0;
for (var key in kv) {
    if (kv.hasOwnProperty(key)) {
        var val = kv[key];
        while (val-- > 0) {
            list_of_objects[index].kv = key;
            index++;
        }
    }    
}