2016-01-11 10 views
5

Also habe ich eine Reihe von Objekten;Array-Element nach Objektschlüssel verschieben

[ 
    { 
     "foo": 2, 
     "bar": "test" 
    }, 
    { 
     "foo": 19, 
     "bar": "value" 
    }, 
    { 
     "foo": 7, 
     "bar": "temp" 
    } 
] 

Ich brauche ein Objekt mit einem bestimmten Wert von foo zu dem Anfang des Arrays zu bewegen. Der Wert befindet sich immer im Objekt, aber es gibt keine Garantie dafür, dass das Objekt im Array enthalten ist.

So nach moveToFront(19); zum Beispiel läuft, würde ich folgende Voraussetzungen erfüllt sein:

[ 
    { 
     "foo": 19, 
     "bar": "value" 
    }, 
    { 
     "foo": 2, 
     "bar": "test" 
    }, 
    { 
     "foo": 7, 
     "bar": "temp" 
    } 
] 

Wie würde ich mich über das tun dies?

+0

es kann eine bessere Datenstruktur als ein Array geben, was sind Ihre Anforderungen/Was versuchen Sie zu tun? Je nachdem, wie oft Sie das Array bewegen müssen und wie groß es ist, könnte dies schnell teuer werden. – James

+0

warum? was versuchst du zu tun, dass du denkst, dass du Elemente im Array überhaupt verschieben musst? –

+0

Was ist der Zweck des Objekts, das sich vor dem Array befindet? – Monkpit

Antwort

9

Das sollte ziemlich trivial sein, Sie suchen Ihr Array, bis Sie das Element finden, das Sie suchen, dann Sie splice es heraus und unshift es zurück zum Anfang. Etwas wie folgt aus:

// foo is the target value of foo you are looking for 
// arr is your array of items 
// NOTE: this is mutating. Your array will be changed (unless the item isn't found) 
function promote(foo, arr) { 
    for (var i=0; i < arr.length; i++) { 
     if (arr[i].foo === foo) { 
      var a = arr.splice(i,1); // removes the item 
      arr.unshift(a[0]);   // adds it back to the beginning 
      break; 
     } 
    } 
    // Matching item wasn't found. Array is unchanged, but you could do something 
    // else here if you wish (like an error message). 
} 

Wenn es kein Element mit einem passenden foo Wert ist, dann wird dies nichts tun Array. Sie können das mit einer Fehlermeldung umgehen, falls gewünscht.

0

Sie können das Array iterieren, das richtige Element finden, es spleißen und den Rest des Arrays mit dem gespleißten Array verbinden.

var collection = [ 
    { 
    foo: 15, 
    bar: true 
    }, 
    { 
    foo: 19, 
    bar: false 
    } 
]; 

function moveToFront(x) { 
    for (var i = 0; i < collection.length; i++) { 
    if (collection[i].foo === x) { 
     collection = collection.splice(i, 1).concat(collection); 
     break; 
    } 
    } 
} 

moveToFront(19); 

console.log(collection); 
+2

Beachten Sie, dass dies auch das ursprüngliche Array kopiert, anstatt es zu mutieren. –

0

Suchen Sie einen beliebigen Wert in jeder Eigenschaft, erste Übereinstimmung gewinnt. Es scheint sehr schnell zu sein, weil die Methode 'some' verwendet wird und die Iteration über das Array unterbrochen wird, wenn die Bedingung erfüllt ist.

'some' führt die Callback-Funktion für jedes im Array vorhandene Element einmal aus, bis eine gefunden wird, in der Callback einen wahren Wert zurückgibt. Wenn ein solches Element gefunden wird, gibt some() sofort true zurück. Mutation ist vorhanden ...

var collection = [ 
    { 
     "foo": 2, 
     "bar": "test" 
    }, 
    { 
     "foo": 19, 
     "bar": "value" 
    }, 
    { 
     "foo": 7, 
     "bar": "temp" 
    } 
]; 


function moveToFront(searchValue) { 

    var idx, exists; 

    for (idx = 0; idx < collection.length; idx++) { 
      exists = Object.keys(collection[idx]).some(function (key) { 
      return collection[idx][key] === searchValue 
     }); 
     if (exists) break; 
    } 

    collection.unshift(collection[idx]); 
    collection.splice(idx + 1, 1); 

} 

moveToFront("temp"); // or moveToFront(19); or move whatever 
console.log(collection); 
0

Noch eine andere Lösung. Mutation in place ...

var collection = [ 
    { 
     "foo": 2, 
     "bar": "test" 
    }, 
    { 
     "foo": 19, 
     "bar": "value" 
    }, 
    { 
     "foo": 7, 
     "bar": "temp" 
    } 
]; 


function moveToFront(property, value, col) { 
    col.reduce(function (prev, current, idx, obj) { 
     if (current[property] != value) { 
      return obj; 
     } else { 
      obj.unshift(obj[idx]); 
      obj.splice(idx + 1, 1); 
     } 
    }); 
} 

moveToFront('foo', 7, collection); 
console.log(collection); 
4

Wenn Sie bereits verwenden lodash in Ihrem Projekt wird die findIndex Methode hilfreich sein:

var data = [ 
 
    { 
 
     "foo": 2, 
 
     "bar": "test" 
 
    }, 
 
    { 
 
     "foo": 19, 
 
     "bar": "value" 
 
    }, 
 
    { 
 
     "foo": 7, 
 
     "bar": "temp" 
 
    } 
 
]; 
 

 
// find target index (using lodash) 
 
var itemIndex = _.findIndex(data, {foo:19}); 
 
// new index, no removal, detach the item and return it 
 
data.splice(0, 0, data.splice(itemIndex, 1)[0]); 
 

 

 
// print result 
 
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Dies bewegt die Array Objekt mit dem Schlüssel "foo": 19 am Anfang des Arrays.