Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading