0

Ive been trying to combine two items together on each loop, in the result there is a null, how do i check the "items" so not to get null's?

var oTitle = [],
items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i=0; i < items.length; i++) {
 oTitle[i] = {
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
 };
}


console.log(JSON.stringify(oTitle)); 

// [{"one":"a1","two":"a2"},null,{"one":"b1","two":"b2"},null,{"one":"c1","two":"c2"}]
david
  • 4,218
  • 3
  • 23
  • 25

2 Answers2

3

Because you change the i in the for loop's body. When you call items[++i], it actually changes the i. And at the second iteration your i is not 1, but it is 2.

oTitles 0 index is ready, but at the second iteration i is 2. So you have values at 0 2 4 and so on. And for the indexes of 1,3,5 and other it has no values, so why it prints you null.

Actually for those indexes your array will contain not null, but undefined. But because you have used JSON.stringify, it converts undefined to null.

To achieve the expected result, you need to keep another variable for the indexing of your array or use push method of the array for indexing itself.

INDEX

var oTitle = [];
var index = 0;
items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i=0; i < items.length; i++) {
 oTitle[index] = {
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
 };
 index++;
}


console.log(JSON.stringify(oTitle)); 

PUSH

var oTitle = [];
items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i=0; i < items.length; i++) {
 oTitle.push({
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
 });
}


console.log(JSON.stringify(oTitle));
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • first snippet's last `index++` is wrong, it will cause each loop skip a number which will generate: `0,1`, `3,4`, `6,7`....... – Sinux Aug 17 '17 at 03:06
1

Just use push() and let the indexing of new array take care of itself

var oTitle = [],
  items = ['a1', 'a2', 'b1', 'b2', 'c1', 'c2'];

for (var i = 0; i < items.length; i++) {
  oTitle.push({
    one: '' + items[i], // items[i].value
    two: '' + items[++i]
  });
}

console.log(JSON.stringify(oTitle, null, ' '))
charlietfl
  • 170,828
  • 13
  • 121
  • 150