0

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.

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Mohaideen
  • 209
  • 1
  • 2
  • 13
  • Look at: http://stackoverflow.com/questions/917904/how-do-add-to-a-key-value-to-javascript-object – Choo Hwan Feb 24 '17 at 05:55
  • Or here: http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object – Choo Hwan Feb 24 '17 at 05:55
  • What exactly *if it is exceeds 5 mins* means for you? What do you want to compare your `data[0]["t"]` to? Because obviously all of them exceed 5minutes (by years). Do you want to compare one item to the next, like `data[1]["t"] - data[0]["t"] > 5 * 60 * 1000`, and if so, insert the `null` object between them, so `data[1]` becomes `data[2]`? – wscourge Feb 24 '17 at 06:35
  • @wscourge, yes same expectation only, it should change from data[1] to data[2] nd comparing by t – Mohaideen Feb 24 '17 at 07:23
  • I dont understand your comment since *nd comparing by t*. Could you please explain what exactly does *if it is exceeds 5 mins* mean? – wscourge Feb 24 '17 at 07:30

1 Answers1

1

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.

Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71