Search code examples
javascriptarraysjavascript-objects

Move Javascript array key forward?


I have 2 items in my object, 1 and 2.

structure concept

I want to add to each item a second frame and to move the:


second frame -> third frame,


third frame -> fourth frame


(notice that I simplified the question, so I would normally have many frames it shouldn't be harcoded)

window.onload = function() {
    localStorage.clear();
    const myObject = {
        "1": {
            keyframes: [
                {"posX": "0", "posY": "0"},
                {"posX": "150", "posY": "0"},
                {"posX": "300", "posY": "0"}
            ]
        },
        "2": {
            keyframes: [
                {"posX": "0", "posY": "0"},
                {"posX": "150", "posY": "0"},
                {"posX": "300", "posY": "0"}
            ]
        }
    };
    window.localStorage.setItem("myObject", JSON.stringify(myObject));
}

I tried foreach loop but don't know how to implement array modifications from other stackoverflow questions...


Solution

  • Use Array::splice() to insert an element to an array at a specific index:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

    const myObject = {
      "1": {
          keyframes: [
              {"posX": "0", "posY": "0"},
              {"posX": "150", "posY": "0"},
              {"posX": "300", "posY": "0"}
          ]
      },
      "2": {
          keyframes: [
              {"posX": "0", "posY": "0"},
              {"posX": "150", "posY": "0"},
              {"posX": "300", "posY": "0"}
          ]
      }
    };
    
    const frame = {newFrame: true}; // fill it with your needed data
    
    Object.values(myObject).forEach(({keyframes}) => keyframes.splice(1, 0, frame)); // insert as a second frame
    
    $result.textContent = JSON.stringify(myObject, null, 4);
    <pre id="$result"></pre>