Move object element position in javascript

后端 未结 3 1013
旧巷少年郎
旧巷少年郎 2021-01-25 12:13

I\'m trying to find a way to move an object element to a specific position.

For example, I\'ve this object :

{
    \"element1\" : {} // object,
    \"el         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 12:52

    JavaScript objects don't have ordering. You should use an array of objects instead.

    var arr = [
      { id: 'element1' },
      { id: 'element2' },
      { id: 'element3' }
    ]
    

    You could then reorder it something like:

    var first = arr.splice(0, 1);
    arr.push(first);
    

    Maybe you could then grab specific elements based on id:

    var out = arr.filter(function (el) {
      return el.id === 'element1';
    });
    

提交回复
热议问题