2016-04-15 22 views
0

我有一个很长的数据列表的JSON,我需要添加硬编码ID(静态)。我想知道如何在像gulp这样的工具中自动执行此过程?我希望它给任务一个文件并修改其内容(如下所示),然后用更新的数据永久保存该文件。自动修改JSON数据并保存在构建

这就是数据的模样,例如: -

[ 
    { 
    "title": "Lorem ipsum", 
    "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit" 
    }, 
    { 
    "title": "Maecenas ac elit", 
    "text": "Maecenas ac elit vitae lorem interdum tincidunt" 
    } 
] 

这里就是我正在寻找的回报: -

[ 
    { 
    "id" : "1", 
    "title": "Lorem ipsum", 
    "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit" 
    }, 
    { 
    "id" : "2", 
    "title": "Maecenas ac elit", 
    "text": "Maecenas ac elit vitae lorem interdum tincidunt" 
    } 
] 
+0

你在使用什么情况下该JSON?如果你使用吞咽,它需要永久保存在某个地方吗? – Shakespeare

+0

@OwenAyres,是我永久保存这些数据,在将来我再次获得相同的数据,我需要静态添加ID :( – Syed

回答

1

使用Array#forEach(),并且该索引为id属性递增。

var array = [{ "title": "Lorem ipsum", "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit" }, { "title": "Maecenas ac elit", "text": "Maecenas ac elit vitae lorem interdum tincidunt" }]; 
 

 
array.forEach(function (a, i) { 
 
    a.id = (i + 1).toString(); 
 
}); 
 

 
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

+0

感谢工作。获取Id的现在添加:)可以在字符串中添加数字( “2”)并移到“标题”上面? – Syed

+1

字符串是没有问题的。但对象有(直到es6)没有秩序。如果你想改变orde,那么每个n对象都必须按照想要的顺序进行重建。我不推荐。 –

+1

谢谢..这是非常有帮助的。 – Syed

0

,如果你的JSON对象的ID被分配排序顺序则没有必要将循环翻一番,使用索引+ 1

例如:http://json.live/173fqW

var arr = [{},{},{},{}]; 

for(var i = 0; i < arr.length; i++) 
{ 
    var obj = arr[i]; 
    var id = i+1; //<<-- this is the ID (array stars from 0 we added +1 to start from 1 
}