user91579631 user91579631 - 1 month ago 10
Node.js Question

Append serial number property to array of objects in javascript

I have an array of objects in javascript.

var obj_arr =
[{
DATA_ID: 281,
DATA_NAME: 'CIM',
DATA_STATE: '0'
},
{
DATA_ID: 382,
DATA_NAME: 'CIMx',
DATA_STATE: '0'
},
{
DATA_ID: 482,
DATA_NAME: 'CIMy',
DATA_STATE: '1'
}]


I would like to append a serial number to each of the object in this array. The appended object will look something like this;

var obj_arr_appended =
[{
SERIAL_NO: 1,
DATA_ID: 281,
DATA_NAME: 'CIM',
DATA_STATE: '0'
},
{
SERIAL_NO: 2,
DATA_ID: 382,
DATA_NAME: 'CIMx',
DATA_STATE: '0'
},
{
SERIAL_NO: 3,
DATA_ID: 482,
DATA_NAME: 'CIMy',
DATA_STATE: '1'
}]


The serial number will auto-increment. I am using node.js v6

Answer

This code should work.

var obj_arr = 
    [{
        DATA_ID: 281,
        DATA_NAME: 'CIM',
        DATA_STATE: '0'
    },
    {
        DATA_ID: 382,
        DATA_NAME: 'CIMx',
        DATA_STATE: '0' 
    },
    {
        DATA_ID: 482,
        DATA_NAME: 'CIMy',
        DATA_STATE: '1' 
    }]    

    for (let i = 0; i < obj_arr.length; i++) {
            obj_arr[i]["SERIAL_NO"] = i;
        }

    console.log(obj_arr);