0

Suppose I have array of object:

originalData = [
  {
    "id": 1
  },
  {
    "id": 2
  },
  {
    "id": 3
  },
  {
    "id": 4
  },
  {
    "id": 5
  },
  {
    "id": 6
  }
]

And I have array of string:

newData = ['1','2','3']

How do I push newData to originalData sequentially?

Expected result should be like so:

originalData = [
  {
    "id": 1,
    "color":'1'
  },
  {
    "id": 2,
    "color":'2'
  },
  {
    "id": 3,
    "color":'3'
  },
  {
    "id": 4,
    "color":'1'
  },
  {
    "id": 5,
    "color":'2'
  },
  {
    "id": 6,
    "color":'3'
  }
]

Here's my workaround:

originalData.forEach(function (object,i) {
    object.color = newData[i]
});
2
  • 1
    What is wrong with your "workaround"? Commented Sep 29, 2016 at 0:18
  • @JuanMendes, Because the workaround would only set color to the first 3 members of the originalData. The rest members would have the color set to undefined. Commented Mar 5, 2017 at 11:20

2 Answers 2

1

Use a variable j and reset it over time.

var j = 0;
originalData.forEach(function (object,i) {
    object.color = newData[j];
    j += 1;
    if(j > newData.length)
        j = 0;
});
Sign up to request clarification or add additional context in comments.

1 Comment

What's different between this and what the OP posted?
0

Reset the counter dynamically depending on the newData array length.

originalData = [{"id": 1},{"id": 2},{"id": 3},{"id": 4},{"id": 5},{"id": 6}];
newData = ['1','2','3'];
for(var i = 0, j=0; i < originalData.length; i++, j++) {
    originalData[i].color = newData[j];
    if(j == newData.length -1){
        j = -1;
    }
}

console.log(originalData);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.