简体   繁体   English

使用键值对填充嵌套数组

[英]Populating Nested Arrays with Key value pairs

I have a nested array structure that looks like this below.我有一个如下所示的嵌套数组结构。 Lets call it arr:让我们称之为 arr:

嵌套数组结构

The innermost array has a key and value pair.最里面的数组有一个键值对。 But as it can be seen, the values are only from 3-7.但可以看出,这些值仅从 3-7 开始。 I need to fill this innermost array with values 0-9 in the key column and populate them to 0 if the key doesn't already exist.我需要在键列中用值 0-9 填充这个最里面的数组,如果键不存在,则将它们填充为 0。 I tried creating a separate array(target) with values [0,9] to check against but have been unsuccessful.我尝试创建一个单独的数组(目标),其值为 [0,9] 来检查但没有成功。 I tried to do something like this but I am getting an error:我试图做这样的事情,但我收到一个错误:

        var target = [0,1,2,3,4,5,6,7,8,9];
    
        for(let i =0; i < target.length; i++){
            for(let j =0; j < arr.length; j++){
                for(let k =0; k < arr[j].values.length; k++){
                        if (miss_rate_arr[i] in rating_count[j].values[k].key === false){
                         rating_count[j].values.push({key:miss_rate_arr[i], value:0});
                     }
                }
            }
        }
        console.log(rating_count);

This is not only checking that particular value at that 0 location and I understand the problem.这不仅是检查那个 0 位置的特定值,而且我理解这个问题。 I am just not sure how to fix it.我只是不知道如何解决它。 I am expecting the end result to look something like this below.我期待最终结果看起来像下面这样。 Thank you in advance先感谢您

在此处输入图片说明

I'm not exactly sure what youre going for, If you're going for a more general approach and want to keep the target array, this is more like what you posted, and you'd need to sort it afterwards to get the array in the order you posted..我不确定您要做什么,如果您要采用更通用的方法并希望保留目标数组,则这更像是您发布的内容,之后您需要对其进行排序以获取数组按照你发布的顺序..

let target = [0,1,2,3,4,5,6,7,8,9];
for(let i = 0; i < target.length; i++){
    if (arr.filter(x => x.key == target[i]).length == 0){
        arr.push({key:target[i], value:0});
    }
}
arr.sort((a,b) => a.key - b.key);

But if target is always 0-9, you could skip the target array and just loop from 0 to the max key you're aiming for.但是如果目标总是 0-9,你可以跳过目标数组,只从 0 循环到你想要的最大键。 that way the test for the value is more simple (you can just check if the key matches the index) and since you have to add it at the correct index, you keep it sorted..这样对值的测试就更简单了(您可以只检查键是否与索引匹配),并且由于您必须将其添加到正确的索引处,因此您可以将其排序。

let maxKey = 9;
for(let i = 0; i <= maxKey; i++){
    if (arr.length > i && arr[i].key != i || arr.length == i){
        arr.splice(i, 0, {key: i, value:0});
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM