2

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

2 Answers 2

3

With array.map you can run a function on each element:

var obj_arr_appended = obj_arr.map(function(currentValue, Index) {
   currentValue.SERIAL_NO = Index
   return currentValue
})
Sign up to request clarification or add additional context in comments.

1 Comment

I always loved the elegance of FP-style answers. I prefer your answer to mine:). Upvoted
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.