cinafoy881
cinafoy881

Reputation: 15

Json - create an ID column that auto increment

I'm building a json object from 2 dataset and I need to add a column (ID) with a unique value, I have thought that having an auto increment ID (1,2,3,4..) value will be great

This is how I'm building my Json object with JavaScript

 var output = [];
                    for (var rowIdx = 0; rowIdx < csv.length; rowIdx++) {
                        var row = {};
                        for (var fieldIdx =0; fieldIdx < fields.length; fieldIdx++) {
                            var field = editor.field( fields[fieldIdx] );
                            var mapped = data[ field.name() ];
                            row[field.name()] = csv[rowIdx][mapped];
                        }
                        output.push(row);
                    }

var json =  JSON.stringify(output);

console.log(json)

and this is my JSON: PLEASE NOTE: I want to add "id": "1" column whose value will auto increment for each record

[
        {
            "id": "1", <--- DESIRED
            "title": "Hello World",
            "artist": "John Smith",
            "genre": "pop",
            "week": "4",
            "highest_rating": "3",
            "year": "2014",
            "youtube": "www"
            ]
        },
        {
            "id": "2", <--- DESIRED
            "title": "Lorem Ipsum",
            "artist": "John Smith",
            "genre": "pop",
            "week": "4",
            "highest_rating": "3",
            "year": "2014",
            "youtube": "www"
            ]
        }
    ]

Upvotes: 0

Views: 4044

Answers (2)

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

you can do this row.id = (rowIdx + 1);

var output = [];
for (var rowIdx = 0; rowIdx < csv.length; rowIdx++) {
    var row = {};
    for (var fieldIdx = 0; fieldIdx < fields.length; fieldIdx++) {
        var field = editor.field(fields[fieldIdx]);
        var mapped = data[field.name()];
        row[field.name()] = csv[rowIdx][mapped];
    }

    row.id = (rowIdx + 1); // <--- this line
    output.push(row);
}

var json = JSON.stringify(output);

console.log(json);

Upvotes: 1

Oner T.
Oner T.

Reputation: 413

You can increment an i number starting from 0, for Id of each object in the output array. For example:

for(let i=0; i<output.length; i++)
{ output[i].id=i+1;}

Upvotes: 1

Related Questions