Mohaideen
Mohaideen

Reputation: 209

How to append a new item to same index in same array inside the for loop

i have obj of array

var data = [{
    value: 1,
    t: 1487203500000
}, {
    value: 2,
    t: 1487213700000
}];

here, i need to compare t obj at inside a loop, if it is exceeds 5 mins, then i need to create a one item with value of null and append into that array.

Expected result will be

var data = [{
    value: 1,
    t: 1487203500000
}, {
    value: null,
    t: null
} {
    value: 2,
    t: 1487213700000
}];

while appending i need to push into same index and existing value should be readjusted.

Upvotes: 0

Views: 1313

Answers (1)

Raman Sahasi
Raman Sahasi

Reputation: 31841

You can use array.splice() for this

The splice() method adds/removes items to/from an array.

var data = [{
    value: 1,
    t: 1487203500000
}, {
    value: 2,
    t: 1487213700000
}];

//  put your index here
//          v
data.splice(1, 0, {value: null, t: null});

console.log(JSON.stringify(data, 0, 8));

In this code

data.splice(1, 0, {value: null, t: null});

1st Parameter (1) -> indicates the position where you want to insert.
2nd Parameter (0) -> indicates how many elements you want to remove.
3rd Parameter ({obj}) -> is the object which we want to insert at position 1.

Upvotes: 1

Related Questions