[英]Converting an array of objects to a nested object
I've searched stack overflow quite a lot but cannot get the information needed, hence the question. 我已经搜索了很多堆栈溢出问题,但无法获得所需的信息,因此是一个问题。
As jsonapi expects all the information to be in the form of objects. 因为jsonapi期望所有信息都以对象的形式出现。
I want to convert : 我想转换:
[{"id":2,"quantity":2},{"id":1,"quantity":2}]
to 至
{"0" : {"id":2,"quantity":2}, "1" : {"id":1,"quantity":2}}
Solution: If anyone needs help and doesn't want to get down voted for merely asking a question out of confusion. 解决方案:如果有人需要帮助,又不想因为困惑而问一个问题而被投票否决。
function toObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i)
if (arr[i] !== undefined) obj[i] = arr[i];
return obj;
}
The object you desire isn't valid. 您想要的对象无效。 All JSON objects work by key,value pair hence this wouldn't work :
所有JSON对象均按键,值对起作用,因此这不起作用:
{
{"id":2,"quantity":2},
{"id":1,"quantity":2}
}
Because you don't have any keys in the root object. 因为您在根对象中没有任何键。 You could do this though :
您可以这样做:
{
"key1": {"id":2,"quantity":2},
"key2": {"id":1,"quantity":2}
}
Does the difference seem clear to you ? 差异对您来说似乎很明显吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.