[英]JS array of arrays to object
I have a JS array (shown 4 examples actual has 66 )我有一个 JS 数组(显示 4 个示例,实际有 66 个)
[["A","Example1"],["A","Example2"],["B","Example3"],["B","Example4"]]
that I am trying to get into an object for a multi select drop down menu:我试图进入一个多选下拉菜单的对象:
var opt = [{
label: 'A', children:[
{"label":"Example1","value":"Example1","selected":"TRUE"},
{"label":"Example2","value":"Example2","selected":"TRUE"}
]
},
{
label: 'B', children:[
{"label":"Example3","value":"Example3","selected":"TRUE"},
{"label":"Example4","value":"Example4","selected":"TRUE"}
]
}
]
Is there a easy way to do this ?有没有一种简单的方法可以做到这一点?
Updated: Using reduce()
and filter()
to get expected results.更新:使用reduce()
和filter()
获得预期结果。
const result = [['A', 'Example1'], ['A', 'Example2'], ['B', 'Example3'], ['B', 'Example4']].reduce((acc, cur) => { const objFromAccumulator = acc.filter((row) => row.label === cur[0]); const newChild = {label: cur[1], value: cur[1], selected: 'TRUE'}; if (objFromAccumulator.length) { objFromAccumulator[0].children.push(newChild); } else { acc.push({label: cur[0], children: [newChild]}); } return acc; }, []); console.log(result);
Here's a rather efficient and concise take on the problem using an object as a map:下面是使用对象作为地图来解决这个问题的一个相当有效和简洁的方法:
const data = [["A","Example1"],["A","Example2"],["B","Example3"],["B","Example4"]]; const opt = data.reduce((results,[key,val]) => { if(!results[0][key]) //first element of results is lookup map of other elements results.push(results[0][key] = { label: key, children: [] }); results[0][key].children.push({ label: val, value: val, selected:"TRUE" }); return results; }, [{}]).slice(1); //slice off map as it's no longer needed console.log(opt);
Something like this should work:这样的事情应该工作:
const raw = [["A","Example1"],["A","Example2"],["B","Example3"],["B","Example4"]];
const seen = new Map();
const processed = raw.reduce((arr, [key, label]) => {
if (!seen.has(key)) {
const item = {
label: key,
children: []
};
seen.set(key, item);
arr.push(item);
}
seen.get(key).children.push({
label,
value: label,
selected: "TRUE"
})
return arr;
}, []);
console.log(processed);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.