我需要能够规范化 javascript 对象或将其展平,我希望能够使用 lodash 做一些事情,但我不知所措。我尝试编写自己的转换器,但它似乎太复杂了,我认为 lodash 可以做这样的事情。
我正在放置我拥有的原始阵列,它有 3 个带有子阵列的项目。 (见下文)
这是我所期望的(创建我的新对象),因此所有内容都被展平并添加到“名称”(请参阅下面的 testProduct1 和 testProduct2),如果没有可用的颜色和位置,则名称只是原始名称(请参阅下面的 testProduct3)。
{
name: ‘testProduct1 RED NewYork’
},
{
name: ‘testProduct1 RED London’
},
{
name: ‘testProduct1 YELLOW NewYork’
},
{
name: ‘testProduct1 YELLOW London’
},
{
name: ‘testProduct2 WHITE NewYork’
},
{
name: ‘testProduct2 WHITE London’
},
{
name: ‘testProduct3’
}
这是原始数组的例子
{
name: ‘testProduct1’,
colors: [
‘RED’,
‘YELLOW’
],
locations: [
‘New York’,
‘London’
]
},
{
name: ‘testProduct2’,
colors: [
‘WHITE’
],
locations: [
‘New York’,
‘London’
]
},
{
name: ‘testProduct3’,
}
最佳答案
这是一个纯 Javascript 解决方案。
var data = [{ name: 'testProduct1', colors: ['RED', 'YELLOW'], locations: ['New York', 'London'] }, { name: 'testProduct2', colors: ['WHITE'], locations: ['New York', 'London'] }, { name: 'testProduct3', }],
flat = function (array) {
var order = ['colors', 'locations'],
r = [];
array.forEach(function (a) {
function getParts(parts) {
if (parts.length >= order.length) {
parts.unshift(a.name);
r.push({ name: parts.filter(Boolean).join(' ') });
return;
}
(a[order[parts.length]] || ['']).forEach(function (b) {
getParts(parts.concat(b));
});
}
getParts([]);
});
return r;
}(data);
document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');
关于javascript - 使用 LoDash 或类似工具规范化/展平 JS 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36065781/