0

There are many objects in the JSON file that look like I have shown below. I want to give an index number starting from 0 for each of these objects. How can I do it?

[
  {
    "language": "Python",
    "created": "2018-8-27 14:50:31",
    "evaluated": true,
    "hiddenCode": false
  },
  ...
]
3
  • What is the reason for adding the IDs to unique Json keys? I don't see the use of an ID as you can access the value with the object key itself. Commented Aug 27, 2018 at 12:04
  • exactly what I want to do is to give each object a place called "index" and start the value of this "index" from 0 Commented Aug 27, 2018 at 12:06
  • iterating the object with object.keys would be helpful for you. Object.keys(objectName).forEach((each, index) => {/* Your code */}) Commented Aug 27, 2018 at 12:12

3 Answers 3

2

You can use Array.prototype.map() (MDN) to get new, indexed, array.

var array = [{
  "language": "Python1",
  "created": "2018-8-27 14:50:31",
  "evaluated": true,
  "hiddenCode": false
}, {
  "language": "Python2",
  "created": "2018-8-27 14:50:31",
  "evaluated": true,
  "hiddenCode": false
}]

const indexed = array.map((item, index) => Object.assign(item, { index }))

console.log(indexed)

Sign up to request clarification or add additional context in comments.

Comments

1

You can loop on the objects and add new property,

var array =[   {
        "language": "Python1",
        "created": "2018-8-27 14:50:31",
        "evaluated": true,
        "hiddenCode": false
    },  {
        "language": "Python2",
        "created": "2018-8-27 14:50:31",
        "evaluated": true,
        "hiddenCode": false
    }
];
for (i = 0; i < array.length; i++) { 
 array[i]["index "] =i;
}
console.log(array);

2 Comments

I have set this to my own file, but it prints the total number of index numbers, ie each index is output as 39 => "index":39 for each
@jennifercryt: can you add your code so that i can check what is wrong
0

Probably something like this if you use ES,

You should use map to iterate over your objects and add the property in it

var yourObjects =[   {
        "language": "Python1",
        "created": "2018-8-27 14:50:31",
        "evaluated": true,
        "hiddenCode": false
    },  {
        "language": "Python2",
        "created": "2018-8-27 14:50:31",
        "evaluated": true,
        "hiddenCode": false
    }
];

var i = 0;    
 yourObjects.map(
     (obj) => {
          obj['index'] = i;
          i++
          return obj;
     });
console.log(yourObjects);

1 Comment

.map callback function also receives index as a second argument, so no need for extra var i

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.