假设我们有一个带有键/值对对象的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' } }