用动态索引创建Json

时间:2013-08-17 16:30:34

标签: javascript json

我想在循环中创建具有此结构的json:

{ id_foto: 
   [ { firstName: 37, lastName: 'Doe' },
     { firstName: 'Anna', lastName: 'Smith' },
     { firstName: 'Peter', lastName: 'Jones' } ] }

我希望它是变量id_foto

这样:

if (id_foto == n.foto_moderata) {
 // add new { firstName: 'Anna', lastName: 'Smith' }
 } else {
 // create new "node" like
{ id_foto(NEW INDEX): 
       [ { firstName: 37, lastName: 'Doe' },] }
}

最终结果如:

{ 10: 
   [ { firstName: 37, lastName: 'Doe' },
     { firstName: 'Anna', lastName: 'Smith' },
     { firstName: 'Peter', lastName: 'Jones' } ]
11: 
   [ { firstName: fff, lastName: 'fff' },
     { firstName: 'fff', lastName: 'fff' } ]
 }

然后取11个索引的所有用户

1 个答案:

答案 0 :(得分:0)

实现数据的顺序ID的一种方法是创建: -
1.存储你身份的当前价值的地方,
2.增加和返回序列的功能

您可以将当前的id值存储在数据对象中,如下所示: -

{ 
   seq : 11,
   10: 
   [ { firstName: 37, lastName: 'Doe' },
     { firstName: 'Anna', lastName: 'Smith' },
     { firstName: 'Peter', lastName: 'Jones' } ],
   11: 
   [ { firstName: fff, lastName: 'fff' },
     { firstName: 'fff', lastName: 'fff' } ]
}

然后使用以下内容增加&返回下一个序列id

function id_foto() {
   return ++your_object.seq;//get,increment and return incremented value
}