Javascript为每个对象对象json添加一个ID

时间:2018-08-27 11:53:38

标签: javascript json

我有一个问题.Json文件中有很多对象,如下所示。我想为每个对象给出一个从0开始的索引号,我该怎么做?

    {
        "language": "Python",
        "created": "2018-8-27 14:50:31",
        "evaluated": true,
        "hiddenCode": false
    }
]

3 个答案:

答案 0 :(得分:1)

您可以在对象上循环并添加新属性,

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

答案 1 :(得分:0)

如果使用ES,可能是这样的

您应该使用map迭代对象并在其中添加属性

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

答案 2 :(得分:0)

您可以使用Array.prototype.map()MDN)来获取新的索引数组。

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)