这是我的回答:
{
"item": [{
"key": "name",
"value": "john"
}, {
"key": "number",
"value": "1234"
}, {
"key": "price",
"value": [{
"item": [{
"item": [{
"key": "quantity",
"value": "20"
}, {
"key": "price",
"value": "200"
}]
}]
}]
}]
}
需要转换为:
{
"name": "john",
"number": "1234",
"price": {
"quantity": "20",
"price": "200"
}
}
答案 0 :(得分:0)
Trying to get property of non-object

答案 1 :(得分:0)
您可以对item
使用嵌套方法并迭代所有数组并为每个数组调用函数iter
。
此解决方案使用Array#forEach
中的thisArg
作为结果的下一个更深层次的对象。
var data = { "item": [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }] },
result = {};
[data].forEach(function iter(a) {
if ('item' in a) {
a.item.forEach(iter, this);
return;
}
if (Array.isArray(a.value)) {
this[a.key] = {};
a.value.forEach(iter, this[a.key]);
return;
}
this[a.key] = a.value;
}, result);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }