[英]Splitting an array of arrays
I have an array of arrays that looks like this. 我有一个看起来像这样的数组数组。
const data = [ ['list1'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '] ['list2'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '] ['list3'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '] ]
I need to get all of the items between the list1, list2 & list3 and the empty value to build a more structured container so that list1, list2 & list3 include the items as children. 我需要获取list1,list2和list3与空值之间的所有项目,以构建一个结构更强的容器,以便list1,list2和list3将该项目作为子项包括在内。 eg {
例如{
const data2 = { 'list1': {'item1': '1', 'item2': '2', 'item3': '3', 'item4': '4'}, 'list2': {'item1': '1', 'item2': '2', 'item3': '3', 'item4': '4'}, 'list3': {'item1': '1', 'item2': '2', 'item3': '3', 'item4': '4'}, 'list4': {'item1': '1', 'item2': '2', 'item3': '3', 'item4': '4'} }
Whats the most efficient way to query the data array to get the items between the list headers? 查询数据数组以获取列表标题之间的项的最有效方法是什么? I see lodash has a
_.slice
method which takes an index but I can't see a way to use the value of the array as a delimiter. 我看到lodash有一个
_.slice
索引的_.slice
方法,但是我看不到使用数组的值作为分隔符的方法。
You could reduce the whole array by using a closure over a reference to the last object with the given key. 您可以通过对给定键的最后一个对象的引用使用闭包来减少整个数组。
var data = [['list1'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '], ['list2'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '], ['list3'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' ']], result = data.reduce(function (ref) { return function (r, a) { if (1 in a) { ref[a[0]] = a[1]; } else if (a[0].trim()) { r[a[0]] = {}; ref = r[a[0]] } return r; }; }(undefined), {}); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this: 尝试这个:
const data = [ ['list1'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '], ['list2'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '], ['list3'], ['item1', '1'], ['item2', '2'], ['item3', '3'], ['item4', '4'], [' '] ]; var result = {}; var lastList = null; for (var item of data) { if (item.length == 1 && item[0] != ' ') { result[item[0]] = lastList = {}; } else if (lastList != null && item.length == 2) { lastList[item[0]] = item[1]; } } console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.