将json转换为json再添加一个属性

时间:2017-01-05 11:22:05

标签: javascript

我有以下json文件:

[{"genres":"Adventure|Animation|Children|Comedy|Fantasy\r","movieId":1,"title":"Toy Story (1995)"},{"genres":"Children|Fantasy|Musical\r","movieId":2017,"title":"Babes in Toyland (1961)"},{"genres":"Comedy|Fantasy\r","movieId":2253,"title":"Toys (1992)"}]

我需要转换另外一个属性rate,其值为0。

[{"genres":"Adventure|Animation|Children|Comedy|Fantasy\r","movieId":1,"title":"Toy Story (1995)","rate":0},{"genres":"Children|Fantasy|Musical\r","movieId":2017,"title":"Babes in Toyland (1961)","rate":0},{"genres":"Comedy|Fantasy\r","movieId":2253,"title":"Toys (1992)","rate":0}]

1 个答案:

答案 0 :(得分:1)

您可以使用循环将属性添加到对象数组

var myJson = [{"genres":"Adventure|Animation|Children|Comedy|Fantasy\r","movieId":1,"title":"Toy Story (1995)"},{"genres":"Children|Fantasy|Musical\r","movieId":2017,"title":"Babes in Toyland (1961)"},{"genres":"Comedy|Fantasy\r","movieId":2253,"title":"Toys (1992)"}];

myJson.forEach(function(item){
item.rate = 0;
});