在 JavaScript 中将 JSON 数组转换为普通 json
javascriptweb developmentfront end technologyobject oriented programmingjson
假设我们有一个 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' } }