Is there a way to map a value in an object to an array index in javascript?

Assuming that the solution should only work in the latest versions of Chrome, Firefox and Safari as a bonus.

-

I am trying to use an associative array for a large dataset with a knockout. My first attempt made it a true associative array:

[1: {Object}, 3: {Object},...,n:{Object}]

but the knockout was unhappy with the cycle of this. So I tried to trick, hoping that:

[undefined, {Object}, undefined, {Object},...,{Object}]

where in the array is the PK identifier from the database table. This array has a size of about 3.2 thousand Elements, and it will be repeated approximately every 10 seconds, therefore, speed is required. I tried to do this with a splice, for example.

$.each(data, function (index, item) {
    self.myArray.splice(item.PKID, 0, new Object(item));
}

, , PKID 1, myArray[0] . PK 500, 0 .

- var myArray = new Array(maxSize), . - , , javascript.

, , , - . , , , . , , , .

, , ? DOM , , , , 10 . , -.

- : ( new Array(maxLength), 10 , , . , .

- :

<!-- ko foreach: {data: myArray(), afterRender: setInitialTileColor } -->
    <div class="tile" data-bind="attr: {id: 'tileID' + $data.PKID()}">
        <div class="content">
        </div>
    </div>
<!-- /ko -->

:

$.each(data.Updated, function (index, item) {
    var obj = myModel.myArray()[item.PKID];
    //do updates here - need to check what kind of change, how long it been since a change, etc
}
+4
4

, , (0 (), )

arr[obj.PKID] = obj;

( forEach, ), (, 500 )

http://jsfiddle.net/0axo9Lgp/

var data = [], new_data = [];

// Generate sample array of objects with index field
for (var i = 500; i < 3700; i++) {
    data.push({
        PKID: i,
        value: '1'
    });
}

data.forEach(function(item) {
    new_data[item.PKID] = item;
});

console.log(new_data);
console.log(new_data.length); // 3700 but real length is 3200 other items are undefined
+1

. , ( ) , , , , React Mithril.

, .

  • . , , Array forEach, .
  • , , . , PKIds . :

.

var indexes = []
var updated = JSON.parse(response).updated; // example array of updated pkids.
for(var i=0;i<allElements.length;i++){
    if(updated.indexOf(allElements[i].pkid)>-1)
        indexes.push(i);
}

, , , pkid, . , , , pk-id pk-.

indexes allElements .

+1
+1

You might want to consider the publish-subscribe template . Subscribe each item to its unique identifier. When an item needs to be updated, it will receive the event and will update itself. This library may be useful for this. It does not depend on browser events, just arrays, so it should be pretty fast.

+1
source

All Articles