Jim Wu Jim Wu - 4 months ago 8
Javascript Question

Access and change 2d Json Array, Javascript

I'm trying to access and change the data I receive from a JSON api call.

The format of the call is like this:

{
"count": 391,
"value": [
{
"id": "id1",
"name": "name1",
"url": "url1",
"project": {
"id": "projId",
"name": "BT-GIT",
"url": "otherurl",
"state": "wellFormed"
},
"defaultBranch": "master",
"remoteUrl": "remote"
},
{
"id": "id2",
"name": "name2",
"url": "url2",
"project": {
"id": "projId",
"name": "BT-GIT",
"url": "otherurl",
"state": "wellFormed"
},
"defaultBranch": "master",
"remoteUrl": "remote"
},...


and I want to add an extra entry to each "value", such that I have:

{
"id": "id1",
"name": "name1",
"url": "url1",
"project": {
"id": "projId",
"name": "BT-GIT",
"url": "otherurl",
"state": "wellFormed"
},
"defaultBranch": "master",
"remoteUrl": "remote"
"date": "date" <---------
}


I've tried:

$.each(data, function (idx) {
data.value[idx].currentDate = new Date().toJSON().slice(0, 16);
})


and:

$.each(data, function (idx) {
data[1][idx].currentDate = new Date().toJSON().slice(0, 16);
})


any Ideas on how I could remedy this problem?

Much thanks.

Answer

You can do with your existing code but just need slightly tweaking,

var data = {
    "count": 391,
    "value": [{
        "id": "id1",
        "name": "name1",
        "url": "url1",
        "project": {
            "id": "projId",
            "name": "BT-GIT",
            "url": "otherurl",
            "state": "wellFormed"
        },
        "defaultBranch": "master",
        "remoteUrl": "remote"
    }, {
        "id": "id2",
        "name": "name2",
        "url": "url2",
        "project": {
            "id": "projId",
            "name": "BT-GIT",
            "url": "otherurl",
            "state": "wellFormed"
        },
        "defaultBranch": "master",
        "remoteUrl": "remote"
    }]
};

$.each(data.value, function (index,data) {
              data.currentDate = new Date().toJSON().slice(0, 16);
          });
console.log(data);

See Demo : https://jsfiddle.net/mj3vu6s6/4/