在 JavaScript 中将 JSON 数组转换为普通 JSON
假设我们有一个这样的 JSON 数组,其中包含键/值对对象——
const arr = [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }];
我们需要编写一个 JavaScript 函数,用于接收这样一个数组。
该函数应该准备一个新数组,其中将数据简单地针对键值列出,而不是这种复杂的结构。
因此,对于上述数组,输出应如下所示——
const output = { "name": "john", "number": "1234", "price": { "quantity": "20", "price": "200" } };
示例
代码如下——
const arr = [{ "key": "name", "value": "john" }, { "key": "number", "value": "1234" }, { "key": "price", "value": [{ "item": [{ "item": [{ "key": "quantity", "value": "20" }, { "key": "price", "value": "200" }] }] }] }]; const simplify = (arr = []) => { const res = {}; const recursiveEmbed = function(el){ if ('item' in el) { el.item.forEach(recursiveEmbed, this); return; }; if (Array.isArray(el.value)) { this[el.key] = {}; el.value.forEach(recursiveEmbed, this[el.key]); return; }; this[el.key] = el.value; }; arr.forEach(recursiveEmbed, res); return res; }; console.log(simplify(arr));
输出
控制台中的输出如下——
{ name: 'john', number: '1234', price: { quantity: '20', price: '200' } }
广告