简体   繁体   English

如何在 JavaScript 中的嵌套 Arrays 中插入键值对

[英]How to Insert Key Value Pairs inside Nested Arrays in JavaScript

I need to achieve the same output but as you see the length of the ID's array is zero because I cannot achieve this output using push command, it generates errors like:我需要实现相同的 output 但如您所见,ID 数组的长度为零,因为我无法使用push命令实现此 output,它会生成如下错误:

push is not a function

Cannot use indexOf for undefined or false

I need to solve this array with a push command and make the output exactly like below but I cannot use the each function because the length is zero.我需要使用推送命令解决此数组并使 output 与下面完全相同,但我不能使用each function 因为长度为零。

var RepeaterClass = {
    Repeaters: [],
    collectRepeaterValues: function (rep_id, cat_id, element_id) {
        this.Repeaters[rep_id] = this.Repeaters[rep_id] || [];
        this.Repeaters[rep_id][cat_id] = this.Repeaters[rep_id][cat_id] || [];

        if (-1 === this.Repeaters[rep_id][cat_id].indexOf(element_id)) {
            this.Repeaters[rep_id][cat_id].push(element_id);
        }
    },
};

Implementing of this code:这段代码的实现:

ID_1: Array(0)
   category: Array(1)
      0: "dog"
      
   animals: Array(2)
      0: "dog"
      1: "cat"

As others have commented it's not entirely clear what you're asking here.正如其他人所评论的那样,您在这里要问什么并不完全清楚。 This code sort of works if you fix the line var Repeaters =[];如果您修复 var Repeaters =[]; 行,则此代码可以正常工作

I think the confusion is arising because we create Repeaters as an array, but then I think you must be calling collectRepeaterValues with strings for rep_id and cat_id (eg 'ID_1' and 'animals') to get the output you are showing.我认为混淆是因为我们将Repeaters创建为一个数组,但是我认为您必须使用rep_id和cat_id的字符串(例如'ID_1'和'animals')调用collectRepeaterValues才能获得您正在展示的output。 It should be called with numbers if you want to create arrays.如果要创建 arrays,则应使用数字调用它。 You can't access an array element with a string.您不能使用字符串访问数组元素。

If you call with strings JavaScript is going to create object properties on the array when you do Repeaters[rep_id] = Repeaters[rep_id] || []如果您使用字符串调用 JavaScript 将在您执行时在数组上创建 object 属性Repeaters[rep_id] = Repeaters[rep_id] || [] Repeaters[rep_id] = Repeaters[rep_id] || [] . Repeaters[rep_id] = Repeaters[rep_id] || [] That is to say, if we execute the statement Repeaters['ID_1'] = [] in JavaScript it's not doing array assignment even if Repeaters is an array.也就是说,如果我们执行JavaScript中的语句Repeaters['ID_1'] = [] ,即使Repeaters是一个数组,它也不会进行数组赋值。 It will create an object property called ID_1 and makes its value the empty array.它将创建一个名为 ID_1 的 object 属性并将其值设为空数组。

The snippets below show calling the (corrected) object with numbers and with strings and the results.下面的代码片段显示了使用数字和字符串以及结果调用(更正后的)object。

As an aside, the if statement in collectRepeaterValues is not working.顺便说一句,collectRepeaterValues 中的 if 语句不起作用。

Now we're back on what the question really is.现在我们回到真正的问题上来。 Do you want arrays, which have to be indexed by numbers of course, or do you want objects with string properties?您想要 arrays,当然必须按数字索引,还是想要具有字符串属性的对象?

 // CALLING WITH STRINGS var RepeaterClass = { Repeaters: [], // Fixed so it's an object property collectRepeaterValues: function (rep_id, cat_id, element_id) { this.Repeaters[rep_id] = this.Repeaters[rep_id] || []; this.Repeaters[rep_id][cat_id] = this.Repeaters[rep_id][cat_id] || []; if (-1 === this.Repeaters[rep_id][cat_id].indexOf(element_id)) { this.Repeaters[rep_id][cat_id].push(element_id); } } } // What I think you're doing? RepeaterClass.collectRepeaterValues("ID_1", "category", "dog"); RepeaterClass.collectRepeaterValues("ID_1", "animals", "dog"); RepeaterClass.collectRepeaterValues("ID_1", "animals", "cat"); // At the top level RepeaterClass.Repeaters is an empty array with a 'ID_1' property // Array length is zero... console.log(RepeaterClass.Repeaters.length); // 0 // But we have a property ID_1, that is itself an array of zero length with category // and animals properties that are arrays console.log(RepeaterClass.Repeaters.ID_1.category[0]); // dog console.log(RepeaterClass.Repeaters.ID_1.animals[0]); // dog console.log(RepeaterClass.Repeaters.ID_1.animals[1]); // cat // Note that this IS the result at the end of the question // EDIT: You can iterate over the properties with for..in console.log('Iterating categories on ID_1:'); for (var cat_id in RepeaterClass.Repeaters.ID_1) { console.log(cat_id); }

 // CALLING WITH NUMBERS var RepeaterClass = { Repeaters: [], // Fixed so it's an object property collectRepeaterValues: function (rep_id, cat_id, element_id) { this.Repeaters[rep_id] = this.Repeaters[rep_id] || []; this.Repeaters[rep_id][cat_id] = this.Repeaters[rep_id][cat_id] || []; if (-1 === this.Repeaters[rep_id][cat_id].indexOf(element_id)) { this.Repeaters[rep_id][cat_id].push(element_id); } } } // How this code is meant to be called I think RepeaterClass.collectRepeaterValues(0, 0, "dog"); RepeaterClass.collectRepeaterValues(0, 1, "dog"); RepeaterClass.collectRepeaterValues(0, 1, "cat"); // At the top level RepeaterClass.Repeaters is now an array structure console.log(RepeaterClass.Repeaters.length); // 1 console.log(RepeaterClass.Repeaters[0][0][0]); // dog console.log(RepeaterClass.Repeaters[0][1][0]); // dog console.log(RepeaterClass.Repeaters[0][1][1]); // cat

The Only Solution I found is by create another array to store the elements inside the repeater then push it in the main Repeaters array outside the funtion我找到的唯一解决方案是创建另一个数组来存储中继器内的元素,然后将其推送到函数外部的主中继器数组中

But Still cannot achieve it in the same function.但仍然无法在同一个 function 中实现。

var RepeaterClass = {
    
    Repeaters: {},
    validated: {},

    collectRepeaterValues: function( cat_id, element_id ) {
            
        // this.Repeaters[ rep_id ]    = this.Repeaters[ rep_id ] || [];
        this.validated[ cat_id ] = this.validated[ cat_id ] || [];

        if ( -1 === this.validated[ cat_id ].indexOf( element_id ) ) {
            
            this.validated[ cat_id ].push( element_id );
                
        }

    }


    AnotherFunction: function() {

        _.each( REP, function( repDetails, repID ) {

            _.each( repDetails, function( value ) {
                /* 1. Call the Collector */
                collectRepeaterValues( value['cat'], value['id'] );

            } );

            /* 2. push the validated output inside the main array */
            this.Repeaters[ repID ] = this.Repeaters[ repID ] || [];
            this.Repeaters[ repID ] = this.validated;
            
            /* Empty for another session */
            this.validated = {};

        } );


    }

}

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

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